[英]How to center the title in a toolbar (even with toolbar back button displayed)
如何使工具欄中的活動標題居中,以便它還可以顯示工具欄后退按鈕?
目前,我發現最好的解決方案是在顯示后退按鈕時有60dp的余量。
當僅使用后退按鈕時,這對我有用。 在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>
在java代碼中:
int contentInsetStartWithNavigation = mTitleContainer.getContentInsetStartWithNavigation();
mTitleContainer.setContentInsetsRelative(0, contentInsetStartWithNavigation);
我不知道最佳做法是什么,但您可以使用工具欄中的自定義后退按鈕嘗試此解決方法。 布局代碼:
<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>
和活動中的代碼:
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();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.