最近在学习过程中,想实现一个PopupMenu,但是item中的android:icon设置项完全没反应,所以得自己编写代码实现,经过查找资料和尝试,以下代码完美实现PopupMenu显示item中的android:icon,效果图如下:
menu包中的main.xml文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item_add"
android:icon="@drawable/addbutton"
android:title="@string/add"/>
<item
android:id="@+id/item_delete"
android:icon="@drawable/delete"
android:title="@string/delete"/>
</menu>
MainActivity.java文件中相关的内容如下:
btn_optins= (Button) findViewById(R.id.btn_option);
PopupMenu popupMenu=null;
btn_optins.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupMenu=new PopupMenu(MainActivity.this,v);
getMenuInflater().inflate(R.menu.main,popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.item_add:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivity(intent);
finish();
break;
case R.id.item_delete:
if(!dataList.isEmpty()){
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name=dataList.get(position).toString();
dataList.remove(position);
cityDB.removeCity(name);
adapter.notifyDataSetChanged();
//刷新当前界面
Intent intent1 = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent1);
finish();
}
});
}else {
Toast.makeText(MainActivity.this,"当前城市列表为空!请添加城市!",Toast.LENGTH_SHORT).show();
}
break;
}
return true;
}
});
//使用反射,强制显示菜单图标
try {
Field field = popupMenu.getClass().getDeclaredField("mPopup");
field.setAccessible(true);
MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popupMenu);
mHelper.setForceShowIcon(true);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
popupMenu.show();
}
});