自訂Android菜單背景

來源:互聯網
上載者:User

如何自訂Android菜單背景呢? 預設的情況下Android系統的菜單是白色的,下面的例子可以通過自訂的xml布局實現個人化的menu

public class MenuEx extends Activity { private static final String TAG = "android123"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = new MenuInflater(getApplicationContext()); inflater.inflate(R.menu.options_menu, menu); setMenuBackground(); return true; }

關鍵代碼就是重寫Layout類的Factory 方法onCreateView,這裡對比繪製的View來替換系統中的

protected void setMenuBackground(){ Log.d(TAG, "開始設定菜單的的背景"); getLayoutInflater().setFactory( new Factory() { @Override public View onCreateView ( String name, Context context, AttributeSet attrs ) { if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) { //上面這句Android123提醒大家不能有改動,目前來看對於原生android目前這個packageName還沒有變化 try { LayoutInflater f = getLayoutInflater(); final View view = f.createView( name, null, attrs ); //嘗試建立我們自己布局 new Handler().post( new Runnable() { public void run () { view.setBackgroundResource( R.drawable.cwj"_bg); //設定背景為我們自訂的圖片,替換cwj_bg檔案即可 } } ); return view; } catch ( InflateException e ) {} catch ( ClassNotFoundException e ) {} } return null; } }); }}

上面的例子可以輕鬆的替換當前Activity的Menu背景顏色,這裡Android開發網再次提醒大家上面加粗的包名不能隨意改動,如果非原生的Android系統,這句可能根據各個廠商編譯的韌體來靈活處理。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.