如何让标题跨越整个工具栏的宽度?目前文字被菜单项截断。我尝试过尝试不同的xml属性,如
paddingEnd
、contentInsetRight
、titleMarginEnd
,但没有结果。谢谢! :)paddingEnd
、contentInsetRight
、titleMarginEnd
,但没有结果。谢谢! :)通常情况下,标题必须始终适合于工具栏菜单和操作项之间,以便在工具栏折叠时将标题向上移动。
解决此问题的简单方法是在工具栏内放置一个TextView,并将工具栏的背景设置为透明。还要注意我已经将LinearLayout的高度设置为0dp并禁用了工具栏上的阴影(虽然屏幕截图上看不到阴影,因为我在KitKat设备上运行它)。
<!-- App Bar container -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/blue"
android:elevation="2dp"
android:orientation="vertical">
<!-- App Bar -->
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:elevation="0dp"
android:gravity="center"
android:minHeight="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="6dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="Title below the AppBar itself."
android:textColor="#fff"
android:textSize="20sp"/>
</LinearLayout>
这将产生以下结果:
这可能看起来像是两个额外的视图,但请记住,如果您不为ToolBar设置标题,则不会在那里填充TextView。净结果仍然是一个额外的视图。
一个hackish的解决方案
private void fixToolbarTitleBug()
{
fixToolbarTitleBug("mTitleTextView");
}
private void fixToolbarTitleBug(String fieldName)
{
try
{
Field field=Toolbar.class.getDeclaredField(fieldName);
field.setAccessible(true);
TextView titleTextView=(TextView) field.get(toolbar);
Toolbar.LayoutParams params=(Toolbar.LayoutParams) titleTextView.getLayoutParams();
params.width=ScreenSize.width()*3/4; //replace this
titleTextView.setLayoutParams(params);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
用法:在调用setTitle之后,必须调用此函数,否则不起作用,因为mTitleTextView是在您第一次设置工具栏标题之后添加到工具栏中的。
supportActionBar.setTitle(title);
fixToolbarTitleBug();
如果您有一个带标题和副标题的工具栏,您也可以使用以下代码:
private void fixToolbarSubtitleBug()
{
fixToolbarTitleBug("mSubtitleTextView");
}
使用方法:
supportActionBar.setSubtitle(subtitle);
fixToolbarSubtitleBug();