简体   繁体   中英

Center align of text of title bar in Android

I'm new at Android programming so I don't know all the features. As I understood, all generated activities has a title bar which contains app_name string resource. I managed to change title of sole activity but I don't understand how to change alignment of the text of the title. I mean, the're generated like this:

在此处输入图片说明

but I need it to be like this:

在此处输入图片说明

If you are using support toolbar , the approach will be easy. just add a text view inside it and make it centered :

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >


     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" />


    </android.support.v7.widget.Toolbar>

in your activity you can access the title like so:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_top);
TextView Title = (TextView) toolbar.findViewById(R.id.toolbar_title);

To have a centered title in ABS (if you want to have this in the default ActionBar, just remove the "support" in the method names), you could just do this:

In your Activity, in your onCreate() method:

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
getSupportActionBar().setCustomView(R.layout.abs_layout);

xml file

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="my Title"
        android:textColor="#ffffff"
        android:id="@+id/mytext"
        android:textSize="18sp" />

</LinearLayout>

Now you should have an Actionbar with just a title. If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM