工具栏标题全宽显示

7
如何让标题跨越整个工具栏的宽度?目前文字被菜单项截断。我尝试过尝试不同的xml属性,如paddingEndcontentInsetRighttitleMarginEnd,但没有结果。谢谢! :)

制作自定义工具栏,将LinearLayout或FrameLayout放置在工具栏标签内。 - Tushar Pandey
@TusharPandey 这是一个有效的解决方案,但它也会导致额外的2个视图,对于这么小的事情来说有点多余。 - zoltish
在爱情和战争中,一切皆可接受 :-) - Tushar Pandey
1
@TusharPandey 不幸的是 ;) 我最终多了4个视图,对于这么小的东西来说。但这是我目前能找到的最好的解决方法。希望未来有更好的方法。 - zoltish
2个回答

2

通常情况下,标题必须始终适合于工具栏菜单和操作项之间,以便在工具栏折叠时将标题向上移动。

解决此问题的简单方法是在工具栏内放置一个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。净结果仍然是一个额外的视图。


0

一个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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接