PopupMenu使用:
插入头文件:
import java.lang.reflect.Field; import com.android.internal.view.menu.MenuPopupHelper; import android.view.Menu; import android.view.MenuInflater; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.PopupMenu.OnDismissListener; import android.widget.PopupMenu.OnMenuItemClickListener; import android.view.KeyEvent;
代码如下:
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.fm_action_bar_favorite, menu); mFlowMenuItem = menu.findItem(R.id.fm_menu_favorite); return true; } public void showPopupMenu() { mPopupMenu = new PopupMenu(mContext, findViewById(R.id.fm_menu_favorite)); Menu menu = mPopupMenu.getMenu(); mPopupMenu.getMenuInflater().inflate(R.menu.fm_menu_favorite, menu); mPopupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.fm_station_add: showAddNewStationDialog(); break; case R.id.fm_remove_all: showRemoveAllStationDialog(); break; case R.id.fm_return: finish(); break; default: break; } return false; } }); mPopupMenu.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { mFlowMenuItem.setEnabled(true); invalidateOptionsMenu(); } }); try { Field field = mPopupMenu.getClass().getDeclaredField("mPopup"); field.setAccessible(true); MenuPopupHelper mHelper = (MenuPopupHelper) field.get(mPopupMenu); mHelper.setForceShowIcon(true); } catch (IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } mPopupMenu.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU){ mFlowMenuItem.setEnabled(false); showPopupMenu(); return true; } return super.onKeyDown(keyCode, event); }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
super.onBackPressed();
return true;
}
if (item.getItemId() == R.id.fm_menu_favorite) {
item.setEnabled(false);
showPopupMenu();
}
return super.onOptionsItemSelected(item);
}