[英]Toolbar title not showing in Center properly if Back button is enabled
我想在中心顯示toolbar
標題,所以我使用自定義textview
來顯示這樣的標題:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Title"
android:textColor="@android:color/white"
android:textSize="25sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
代碼:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView title = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
title.setText("Title");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
結果:
如果我啟用工具欄的后退按鈕,標題文本不會正確顯示在中心。
如果未啟用工具欄的后退按鈕,則一切正常,即
如果
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
結果:
現在,我還想在工具欄啟用后退按鈕的情況下在中心顯示標題。 如何做到這一點? 任何幫助
1)你需要刪除這個
title.setText("Title");
因為已經在 xml 文件中。
2) 使用
getSupportActionBar().setDisplayShowTitleEnabled(false);
3)為TextView
設置布局重力
android:layout_gravity="center"
編輯:
wrap_content
TextView
高度和寬度更改為wrap_content
。
我想這個問題最簡單的解決方案是將 TextView 的寬度和高度都更改為 wrap_content。 希望它有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.