简体   繁体   中英

Android center custom view in actionbar

Trying to set a custom view for my actionbar, but have the problem that it doesn't fill up the entire width of the actionbar which makes it har for me to center objects. How can i set a custom view in my actionbar that fills up the entire actionbar?

Code for setting up my actionbar:

actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionBar.setCustomView(inflater.inflate(R.layout.actionbar_layout, null));

And my actionbar_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="#EDEDED">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="#FFFFFF"
    android:text="Testing"/>
</RelativeLayout>

You have to set android:layout_width="wrap_content" for your RelativeLayout in your actionbar_layout.xml; this, in conjunction with android:layout_gravity="center", allows to center your custom view in the ActionBar.

As far as I am concerned, the thing is that the upper layout is always streched to the inner view height and weight. You can make it work just by setting layout_height="match_parent" in the TextView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/actionbar_title"
        />
</LinearLayout>

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