[英]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.