Make Android Toolbar text center aligned


By default the Title text in the Android Toolbar is right-aligned, If you want to change it to center, you can do so by creating your own custom ToolBar,

custom_action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/custom_action_bar"
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Title in Center"
        android:textAlignment="center"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

Now in your Activity class, in onCreate() method add the below lines to use your own custom Toolbar.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        ActionBar customActionBar = getSupportActionBar();
        customActionBar.setDisplayShowCustomEnabled(true);
        customActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        customActionBar.setCustomView(R.layout.custom_action_bar);

        setContentView(R.layout.activity_main);
    }

}
Output:
Make Android Toolbar text center
Make Android Toolbar text center


Have Questions? Post them here!



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.