如何在左侧创建带有自定义按钮的工具栏?

How to create toolbar with custom button on the left?

我是 Android 开发的新手,在创建自定义工具栏时遇到了很大的问题。我的要求:

  1. 左侧自定义按钮(图标+文字)
  2. 自定义按钮后的分隔线
  3. 按钮高度应与工具栏相同(无边距)

这是解释我的要求的示例图片:

我尝试使用 actionBar.setCustomView(v); 但它没有解决我的问题:

  1. 右侧按钮有 top/bottom 边距 - 它们小于工具栏
  2. 我无法添加分隔符。
  3. 左键(来自自定义视图)小于工具栏高度。

我的问题:

  1. 我真的需要自定义视图来在左侧添加自定义按钮吗?
  2. 如何在左侧添加分隔线?
  3. 如何使按钮高度与工具栏高度相同?

Toolbar 基本上是一个 FrameLayout,因此您可以在布局标签中添加任何您想要的内容。在您的情况下,类似以下内容似乎就足够了:

layout.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:background="?colorPrimary"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="?attr/actionBarSize"
        android:divider="@drawable/divider"
        android:dividerPadding="8dp"
        android:orientation="horizontal"
        android:showDividers="end">

        <TextView
            android:id="@+id/toolbar_save"
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Subtitle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="?attr/selectableItemBackground"
            android:drawableLeft="@drawable/ic_action_check"
            android:drawablePadding="8dp"
            android:gravity="center_vertical"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:text="Save"
            android:textAllCaps="true" />

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

divider.xml

将此添加到您的 /res/drawable 文件夹。这在上面的代码中用作 LinearLayout 分隔符。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size android:width="1dp" />

    <solid android:color="@android:color/white" />

</shape>

代码

private void setupToolbar() {
    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    // Hide the title
    getSupportActionBar().setTitle(null);
    // Set onClickListener to customView
    TextView tvSave = (TextView) findViewById(R.id.toolbar_save);
    tvSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO
        }
    });
}

右侧项目方面:使用默认的onCreateOptionsMenu方法,并inflate相应的R.menu.*资源即可。

结果

 <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        app:contentInsetStartWithNavigation="0dp"
      />

您还需要 app:contentInsetStartWithNavigation="0dp" 到工具栏