【问题标题】:Adding custom buttons to ToolBar [duplicate]将自定义按钮添加到工具栏 [重复]
【发布时间】:2016-05-25 12:58:39
【问题描述】:

我想知道在浪费时间之后,如何将自定义按钮添加到工具栏/活动栏?如果有人有答案,可以请他/她发给我吗...

【问题讨论】:

  • 您搜索过的内容
  • 只需在 google 上搜索 android 工具栏中的自定义布局

标签: java android


【解决方案1】:

工具栏是一个ViewGroup,你可以在里面添加任何布局。在下面给出的示例中,我使用的是 LinearLayout。

layout.xml

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:titleTextColor="#FFFFFF">

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

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

在java中,你可以访问Button作为

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

Java 类中使按钮可点击

button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click   
            }
        });

【讨论】:

  • 由于android:layout_width="match_parent" 标题仍然在linearLayout下
  • 我建议在 LinearLayout 中使用 TextView 来设置标题,以便它们对齐并正确设置边界。
【解决方案2】:

您可以像下面那样制作自定义工具栏并将任何视图添加到您的工具栏

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >


 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toolbar Title"
    android:layout_gravity="center"
    android:id="@+id/toolbar_title" />


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

【讨论】:

    【解决方案3】:

    由于ToolbarViewGroup 的子类,因此您可以将任何视图放入其中

     <android.support...Toolbar
        android:layout_width=".."
    android:layout_height=".."
        ..
        ...>
    
        <Button
    android:layout_width=".."
    android:layout_height=".." 
        ...
        ...
        />
        </android....Toolbar>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多