android custom Android menu background code

  • 2020-05-09 19:14:38
  • OfStack

 
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 onCreateView, the factory method of the Layout class, to replace View drawn on the system
 
protected void setMenuBackground(){ 
Log.d(TAG, " Start setting the background of the menu "); 
getLayoutInflater().setFactory( new Factory() { 
@Override public View onCreateView ( String name, Context context, AttributeSet attrs ) { 
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) { 
// The above sentence Android123 I want to remind you that you can't change it, but for now it's native android At present the packageName It hasn't changed  
try { 
LayoutInflater f = getLayoutInflater(); 
final View view = f.createView( name, null, attrs ); // Try creating our own layout  
new Handler().post( new Runnable() { 
public void run () { 
view.setBackgroundResource( R.drawable.cwj"_bg); // Set the background to our custom image, replace cwj_bg file  } } ); 
return view; 
} catch ( 
InflateException e ) {} 
catch ( 
ClassNotFoundException e ) {} 
} 
return null; 
} }); }} 

The above example can easily replace the current Activity background color of Menu. Here again, the Android development network reminds you that the bold package name above cannot be changed at will. If the Android system is not native, this sentence may be handled flexibly according to the firmware compiled by various manufacturers.


Related articles: