Search code examples
androidandroid-actionbar

ActionBar align center


I have a problem with my alignment in the ActionBar.

It is centering the Imageview between the icons, but what I want is that it is centering not depend on the buttons but on the whole ActionBar. How can I achieve this?

<?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:layout_gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/action_bar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#fff"
        android:textSize="24sp" />

    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="-10dp"
        android:layout_marginBottom="20dp"
        android:src="@drawable/triptracker_logo"/>
</LinearLayout>

In my java class:

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

Solution

  • What I got from your question is that you want the action bar title to be in center independent of the icon. Use RelativeLayout instead of LinearLayout
    I hope it will work

    <?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:orientation="vertical">
    
    <TextView
        android:id="@+id/action_bar_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="24sp" />
    
    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="-10dp"
        android:layout_marginBottom="20dp"
        android:src="@drawable/triptracker_logo"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_centerInParent="true"/>
    </RelativeLayout>