2015-10-20 38 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」 到工具欄

相關問題