实话说 就个人感觉 Memu 真的很丑 所以今天尝试换掉之
[原理]
1. 保留Menu按键起作用
2. 用ListView显示所有子菜单
[代码 步骤]
1. 定义 menu.xml 仅含有一个ListView 并得到其View
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/mList" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
mview = this.getLayoutInflater().inflate(R.layout.menu, null);
2. 使用PopupWindow作为菜单显示容器 并得到其中的ListView 供后续使用
mpop = new PopupWindow(mview,500,200); mpop.setFocusable(true); mlist = (ListView)mview.findViewById(R.id.mList);
3. 定义List<Map<String,String>> moption 用于存放菜单名字
public void initialMenu(){ moption = new ArrayList<Map<String,String>>(); Map<String,String> map1 = new HashMap<String,String>(); map1.put("Option", "新增"); moption.add(map1); Map<String,String> map2 = new HashMap<String,String>(); map2.put("Option", "删除"); moption.add(map2); Map<String,String> map3 = new HashMap<String,String>(); map3.put("Option", "属性"); moption.add(map3); }
4. 在ListView中显示moption
String[] from = {"Option"}; int[] to = {R.id.text1}; madapter = new SimpleAdapter(this, moption, R.layout.menulayout, from,to); mlist.setAdapter(madapter);
5. 注册Menu弹起事件
public boolean onCreateOptionsMenu(Menu menu) { mpop.showAtLocation(findViewById(R.id.mainlayout), Gravity.CENTER, 30, 40); return false; }
6. 注册Menu子项单击事件 而后关闭之
mlist.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub doMenu(arg2); mpop.dismiss(); } }); public void doMenu(int i){ switch(i){ case 0: break; case 1: break; } Toast.makeText(this, "Menu "+i+" is selected!", Toast.LENGTH_LONG).show(); }
7. emulator 运行截图: