简体   繁体   中英

How to Centralize Title text for Custom Action Bar through Styles.XML

I just created a custom action bar from my styles.xml class that shows up just the way I want it. And I have activated it from the manifest file.

<style name="customStyle" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name="actionBarStyle">@style/customActionBarStyle</item>
        <item name="android:textColorPrimary">@color/titletextcolor</item>
    </style>

    <style name="customActionBarStyle" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="background">@drawable/custom</item>
    </style>

However, I'm trying to find a way to CENTRALIZE the title text on the action bar from the styles.xml file. Please can anyone help with how to do that.

I tried using this: <item name="android:layout_gravity">center</item> . But it had no effect.

Most of the suggestions I've seen online requires creating a toolbar layout separately. But I've done that and Its not what I want because It requires way more code.

Thank you.

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);

abs_layout :

<?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" ).

or with:

getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));

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