Android custom Android menu background code

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.