popup window from android options menu not working

2019-09-02 10:45发布

问题:

Actually I am showing popup window(custom layout) when options menu item clicked and my options menu are bottom to the screen(splitActionBarWhenNarrow).I am getting some exception please help me code:

    switch (item.getItemId()) {
    case R.id.redid:

        Toast.makeText(MainActivity.this,"red color", Toast.LENGTH_SHORT).show();
        break;
    case R.id.blueid:
        Toast.makeText(MainActivity.this,"blue color", Toast.LENGTH_SHORT).show();
        break;
   case R.id.greenid:

  LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View popupview=inflater.inflate(R.layout.popuplayout,null);
  PopupWindow popwindow=new PopupWindow(popupview,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
  popwindow.showAsDropDown(item.getActionView(), 100, 100);  

回答1:

Try in this manner:

    switch (item.getItemId()) {
    case R.id.redid:

        Toast.makeText(MainActivity.this,"red color", Toast.LENGTH_SHORT).show();
        break;
    case R.id.blueid:
        Toast.makeText(MainActivity.this,"blue color", Toast.LENGTH_SHORT).show();
        break;
   case R.id.greenid:
        initiatePopupWindow();
        break;
   }

and outside onCreate() paste this:

private PopupWindow pwindo;

private void initiatePopupWindow() { 
try { 
// We need to get the instance of the LayoutInflater 
LayoutInflater inflater = (LayoutInflater) PopupActivity.this 
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View layout = inflater.inflate(R.layout.popup,(ViewGroup)

findViewById(R.id.popup_element)); 
pwindo = new PopupWindow(layout, 350, 350, true); 
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);

btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup); 
btnClosePopup.setOnClickListener(cancel_button_click_listener);

} catch (Exception e) { 
e.printStackTrace(); 
} 
}

I think in this manner may be your problem will be solved.