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类的工厂方法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;
}
});
}
}
标签:菜单,return,自定义,menu,void,new,Android,public,view
From: https://blog.51cto.com/u_3124497/6914296