如何在工具栏上居中操作菜单

6

我有一个使用拆分操作栏加载操作菜单的应用程序。

我将Action Bar更改为新的工具栏,并使用独立模式中使用的另一个工具栏替换了拆分ActionBar:

Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbarBottom);
toolbarBottom.inflateMenu(R.menu.ab_one_cam);

按照文档规定,操作菜单固定在工具栏的右侧: enter image description here 但我希望图标居中显示在工具栏上,就像分割动作栏一样: enter image description here 如何让操作菜单占用工具栏的所有可用空间? 工具栏专用于此菜单,不会添加其他内容。
答案: 已接受的答案链接到了一个分割工具栏。如果像我一样只有非常简单的需求,那么这段代码就足够好:
public class SplitToolbar extends Toolbar {

    public SplitToolbar(Context context) {
        super(context);
    }

    public SplitToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SplitToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void addView(View child, ViewGroup.LayoutParams params) {
        if (child instanceof ActionMenuView) {
            params.width = LayoutParams.MATCH_PARENT;
        }
        super.addView(child, params);
    }
}

感谢: https://gist.github.com/dodgex/7bc81fd2cbb70a8d5117


请注意:还可以查看以下链接:http://stackoverflow.com/questions/34546160/how-to-enable-split-action-bar/34546493#34546493 - piotrek1543
2个回答

6
在这种情况下,Chris Banes建议使用ActionMenuView而不是Toolbar(请参见下面的链接,回复#6)。除此之外,在此链接中,您可以找到一种解决方案,其中这个人对Toolbar进行了子类化,以便分割正常工作。

https://code.google.com/p/android/issues/detail?id=77632#c2

希望它对你有所帮助!

1
使用线程注释中详细介绍的SplitToolbar就解决了问题: https://gist.github.com/dodgex/7bc81fd2cbb70a8d5117 - grunk

1

我最近几周也一直在寻找这个问题的答案。目前我找到的最接近的解决方案是利用Toolbar只是一个ViewGroup的事实。你所需要做的就是创建一个menu_items布局,它只是一个LinearLayout,里面加上等权重的菜单项即可。我知道这并不是一个理想的解决方案,但我尚未找到在使用默认菜单时如何展开菜单项的方法。

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_btm"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/toolbar_bkgnd"
        android:layout_alignParentBottom="true"
        app:theme="@style/ThemeOverlay.AppCompat.ActionBar" >

        <include layout="@layout/menu_items"/>

        </android.support.v7.widget.Toolbar>

1
你能否仍然使用inflateMenu()和setOnMenuItemClickListener()这个解决方案? - grunk
是的和不是的。如果您正在使用溢出菜单,您仍然可以使用默认方法,但对于其他菜单项,您需要通过XML设置布局并自己监听onClick事件。 - MrEngineer13
没有必要使用工具栏,最好创建一个自定义视图 :( - grunk

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