Copy codeThe Code is as follows: 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;
}
The key code is to override the factory method onCreateView of Layout class. Here, we will compare the drawn View to replaceCopy codeThe Code is as follows: protected void setMenuBackground (){
Log. d (TAG, "Start setting menu background ");
GetLayoutInflater (). setFactory (new Factory (){
@ Override public View onCreateView (String name, Context context, AttributeSet attrs ){
If (name. inclusignorecase ("com. android. internal. view. menu. IconMenuItemView ")){
// The above Android123 reminds you that no change is allowed. Currently, the packageName of native android has not changed.
Try {
LayoutInflater f = getLayoutInflater ();
Final View view = f. createView (name, null, attrs); // try to create our own Layout
New Handler (). post (new Runnable (){
Public void run (){
View. setBackgroundResource (R. drawable. cwj "_ bg); // set the background to a custom image. Replace the cwj_bg file }});
Return view;
} Catch (
InflateException e ){}
Catch (
ClassNotFoundException e ){}
}
Return null;
}});}}
The preceding example can easily replace the Menu background color of the current Activity. Here, the Android Development Network reminds you that the bold package name cannot be changed at will, this statement may be flexibly handled based on firmware compiled by various vendors.