简体   繁体   中英

How to center the title in a toolbar (even with toolbar back button displayed)

How to center the title of an activity in the toolbar in such a way that it works also with the toolbar back button displayed ?

Currently, the best solution I have found is to had a 60dp margin if the back button is displayed.

When using ONLY the back button, this worked for me. In xml:

<android.support.v7.widget.Toolbar
    android:id="@+id/tb_title_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textAllCaps="true"
        android:textColor="#2B2B2B"
        android:textSize="14sp" />

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

In java code:

int contentInsetStartWithNavigation = mTitleContainer.getContentInsetStartWithNavigation();
mTitleContainer.setContentInsetsRelative(0, contentInsetStartWithNavigation);

I don't know how is the best practice, but you can try this workaround using custom back button inside the toolbar. The layout code:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/toolbar_back_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:src="@drawable/ic_back" />

        <TextView
            android:id="@+id/toolbar_title"
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center" />

    </RelativeLayout>

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

and the code in activity:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);

    ImageView backButton = (ImageView) findViewById(R.id.toolbar_back_button);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           finish();
        }
    });

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