2012-03-22 104 views
0

我想在菜單項上顯示徽章。我該怎麼做?Android - 在MenuItems上畫徽章

基本上,我不想畫或使用畫布來這樣做。

+0

你只想與你的菜單項相關聯的圖像.. – 2012-03-22 19:07:43

+0

是,位圖,在右上角 – 2012-03-22 19:15:02

+0

的數字。如果你想要的東西的郵件圖標的..然後,它是複雜的任務並需要通過自定義控件處理,,你可以簡單地有一個按鈕,該圖像的形式與某些文本和重力作爲頂部|右等 – 2012-03-22 19:26:13

回答

0

Android中的選項菜單可以自定義設置背景或更改文字外觀。菜單中的背景和文字顏色無法使用主題和樣式進行更改。

Android源代碼(data\res\layout\icon_menu_item_layout.xml)使用類「com.android.internal.view.menu.IconMenuItem」類的自定義項目作爲菜單佈局。我們可以在上面的類中進行更改以自定義菜單。要達到相同效果,請使用工廠級別LayoutInflater並設置視圖的背景和文本顏色。

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.my_menu, menu); 
    getLayoutInflater().setFactory(new Factory() { 
     @Override 
     public View onCreateView(String name, Context context, AttributeSet attrs) { 
      if (name .equalsIgnoreCase(「com.android.internal.view.menu.IconMenuItemView」)) { 
       try{ 
        LayoutInflater f = getLayoutInflater(); 
        final View view = f.createView(name, null, attrs); 
        new Handler().post(new Runnable() { 
         public void run() { 
          // Set the background drawable 
          view .setBackgroundResource(R.drawable.my_ac_menu_background); 

          // Set the text color 
          ((TextView) view).setTextColor(Color.WHITE); 
         } 
        }); 
        return view; 
       } 
       catch (InflateException e) { 
       } 
       catch (ClassNotFoundException e) { 
       } 
      } 
      return null; 
     } 
    }); 
    return super.onCreateOptionsMenu(menu); 
} 
+0

這幫了我,但它不是我正在尋找什麼 – 2012-04-01 17:07:14

0

菜單項具有屬性圖標,例如:

<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     android:id="@+id/mi_main_preferences" 
     android:title="@string/cmd_preferences" 
     android:icon="@android:drawable/ic_menu_preferences"> 
    </item> 
</menu> 

上面的例子使用系統圖標(偏好菜單)。

+0

但是我怎麼能有bbadge呢 – 2012-03-22 19:17:30

+0

對不起,我的英文不好。圖標和徽章有區別嗎? – 2012-03-23 00:16:36

+0

是的,徽章顯示在圖標的頂部 – 2012-03-23 19:09:25

1

您可以嘗試創建一個LayerListDrawable,將您的常規圖標作爲第一層,將徽章作爲第二層,然後使用setIcon()上的MenuItem

+1

你可以有任何代碼片段來解釋。 PLZ – 2012-03-23 19:09:59