Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 Android 選單背景的實作程式碼

編輯:關於 Android 程式設計

Android 原生的 Options Menu 樣式比較單調,若想換上自訂背景圖,可以透過重寫 Layout 工廠方法來替換系統繪製的 View。以下是一個完整範例。

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;
}

關鍵在於重寫 LayoutInflater 的 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" ) ) {
// 這個包名目前對原生 android 尚未變動,請勿任意修改
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); // 換成自定義圖片即可
}
} );
return view;
} catch ( InflateException e ) {}
catch ( ClassNotFoundException e ) {}
}
return null;
}
});
}

透過這個範例就能輕鬆替換當前 Activity 的 Menu 背景。要特別提醒的是,上面那個 com.android.internal.view.menu.IconMenuItemView 的套件名稱不可隨意改動;若是非原生的 Android 系統,這段可能需要依各廠商固件的實際情況靈活調整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved