2017-04-02 87 views
0

我想顯示一個菜單,文字和圖標始終可見。我定義我的項目佈局如下使用自定義模板的操作欄菜單項

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="?attr/selectableItemBackground" 
    android:clickable="true" 
    android:drawableLeft="@drawable/ic_cart" 
    android:gravity="center" 
    android:orientation="vertical" 
    android:text="(0)" 
    android:drawablePadding="5dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" 
    android:textColor="@android:color/white" /> 

和菜單定義爲以下

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context="com.taptoscan.taptoscan.MainActivity"> 

    <item 
     android:id="@+id/action_sign" 
     android:title="(0)" 
     app:showAsAction="always|withText" 
     app:actionLayout="@layout/menu_sign" /> 

    <item 
     android:id="@+id/action_settings" 
     android:orderInCategory="100" 
     android:title="@string/action_settings" 
     app:showAsAction="never" /> 
</menu> 

我在與能夠在背景上的連鎖反應的問題。它可以工作,但連鎖效果不是圓整的,喜歡定期的菜單圖標。它是方形的,看起來有點醜。在自定義菜單項上看到什麼是實現本機連鎖反應的最佳方式?

編輯:這是什麼樣子

enter image description here

+0

做到這一點的唯一方法是使延伸'TextView'然後應用一些邏輯,使之輪 –

+0

@MohamedRa託管拿出一個解決方案自定義視圖,貼它作爲答案。 –

回答

1

注:更好的解決方案發現,檢查編輯

我想通了。首先,我創建了一個帶圓角的背景繪製的,就像這樣:

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

     <padding 
      android:bottom="5dp" 
      android:left="5dp" 
      android:right="5dp" 
      android:top="5dp" /> 

     <corners android:radius="5dp" /> 

    </shape> 
</ripple> 

在那之後,我設置的TextView的背景從上面的繪製。波紋效果按照預期工作,並且像默認菜單項一樣圓潤。

enter image description here

編輯

進一步自定義菜單項亂搞後,我發現,僅使用一個TextView沒有根元素會導致TextView中的基線後點擊修改另一個菜單項,然後點擊自定義菜單項。該解決方案是使用以下佈局

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:clickable="true" 
    android:background="@drawable/btn_actionbar_icon"> 

    <TextView 
     android:id="@+id/icon_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:drawableLeft="@drawable/ic_cart" 
     android:drawablePadding="5dp" 
     android:gravity="center_vertical" 
     android:padding="10dp" 
     android:text="(0)" 
     android:textColor="@android:color/white" 
     android:textSize="14sp" /> 

</RelativeLayout>