Android编程实现自定义系统菜单背景的方法
程序员文章站
2023-12-18 19:13:10
本文实例讲述了android编程实现自定义系统菜单背景的方法。分享给大家供大家参考,具体如下:
不多说,上图,见代码。
package lab.sodino...
本文实例讲述了android编程实现自定义系统菜单背景的方法。分享给大家供大家参考,具体如下:
不多说,上图,见代码。
package lab.sodino.menutest; import android.content.context; import android.app.activity; import android.os.bundle; import android.os.handler; import android.util.attributeset; import android.view.inflateexception; import android.view.layoutinflater; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.widget.toast; /** * @author sodino e-mail:sodinoopen@hotmail.com * @version time:2011-1-26 下午04:42:04 */ public class menuact extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); } public boolean oncreateoptionsmenu(menu menu) { super.oncreateoptionsmenu(menu); menuinflater inflater = new menuinflater(getapplicationcontext()); inflater.inflate(r.menu.menu, menu); setmenubackground(); return true; } public boolean onoptionsitemselected(menuitem item) { string info = ""; switch (item.getitemid()) { case r.id.menu_add: info = "add"; break; case r.id.menu_delete: info = "delete"; break; case r.id.menu_home: info = "home"; break; case r.id.menu_help: info = "help"; break; default: info = "null"; break; } toast toast = toast.maketext(this, info, toast.length_short); toast.show(); return super.onoptionsitemselected(item); } // 关键代码为重写layout.factory.oncreateview()方法自定义布局 protected void setmenubackground() { menuact.this.getlayoutinflater().setfactory(new android.view.layoutinflater.factory() { /** * name - tag name to be inflated.<br/> * context - the context the view is being created in.<br/> * attrs - inflation attributes as specified in xml file.<br/> */ public view oncreateview(string name, context context, attributeset attrs) { // 指定自定义inflate的对象 if (name.equalsignorecase("com.android.internal.view.menu.iconmenuitemview")) { try { layoutinflater f = getlayoutinflater(); final view view = f.createview(name, null, attrs); new handler().post(new runnable() { public void run() { // 设置背景图片 view.setbackgroundresource(r.drawable.menu_background); } }); return view; } catch (inflateexception e) { e.printstacktrace(); } catch (classnotfoundexception e) { e.printstacktrace(); } } return null; } }); } }
/res/menu/menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_add" android:title="add" android:icon="@drawable/menu_add"></item> <item android:id="@+id/menu_delete" android:title="delete" android:icon="@drawable/menu_delete"></item> <item android:id="@+id/menu_home" android:title="home" android:icon="@drawable/menu_home"></item> <item android:id="@+id/menu_help" android:title="help" android:icon="@drawable/menu_help"></item> </menu>
希望本文所述对大家android程序设计有所帮助。