首页 > 解决方案 > 如何将自定义按钮添加到工具栏

问题描述

我是 Android 开发新手,需要一些帮助 :) 我只是想在工具栏右侧添加自定义按钮。

我看到很少有 LinearLayouts 等解决方案......但我不确定这样做是否正确。

已经检查了 Material design 并找到了 TopBar 但不认为这是我需要的:p

例子: 在此处输入图像描述

谢谢!

标签: javaandroidtoolbar

解决方案


创建自定义工具栏 (toolbar.xml),您可以使用它LinearLayout来容纳您的自定义设计:

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="100dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="right">

                <Button
                    android:id="@+id/button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>
    </android.support.v7.widget.Toolbar>

将自定义工具栏包含到您的 activity.xml 中:

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   layout="@layout/toolbar" />

访问Button

Button button = (Button) findViewById(R.id.button);


button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Your logic  
            }
        });

推荐阅读