本文实例讲述了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;
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() {
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程序设计有所帮助。
您可能感兴趣的文章:Android开发技巧之我的菜单我做主(自定义菜单)android 自定义Android菜单背景的代码Android使用自定义控件HorizontalScrollView打造史上最简单的侧滑菜单Android实现自定义的卫星式菜单(弧形菜单)详解Android实现自定义滑动式抽屉效果菜单Android自定义ViewGroup实现带箭头的圆角矩形菜单Android自定义控件简单实现侧滑菜单效果android自定义popupwindow仿微信右上角弹出菜单效果Android自定义view实现圆形与半圆形菜单Android自定义控件之仿优酷菜单Android自定义VIew实现卫星菜单效果浅析Android自定义控件案例汇总2(自定义开关、下拉刷新、侧滑菜单)Android编程自定义菜单实现方法详解