2015-10-20 37 views
10

我是Android新手,我在创建自定义工具栏时遇到了很多问题。我的要求:左侧如何使用左侧的自定义按钮创建工具栏?

  1. 自定义按钮(图标+文字)后,自定义按钮
  2. 分频器
  3. 按钮的高度应该是相同的工具条(无边框)

下面是示例图像这解释了我的要求: enter image description here

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

  1. 右按钮具有顶部/底部边缘 - 他们比工具栏
  2. 小我无法添加分隔。
  3. 左按钮(自定义视图)小于工具栏高度。

我的问题:

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

你有任何机会,以测试所提供的解决方案? – reVerse

回答

23

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方法和膨胀相应R.menu.*资源。

结果

result image

+1

app:contentInsetStart =“0dp”这解决了我的问题 – umesh

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

您还需要应用:contentInsetStartWithNavigation = “0dp” 到工具栏

相关问题