Android选项菜单弹出窗口无法正常工作

时间:2014-01-07 09:56:27

标签: android popupwindow android-optionsmenu

实际上,当点击选项菜单项并且我的选项菜单位于屏幕底部(splitActionBarWhenNarrow)时,我正在显示弹出窗口(自定义布局)。我得到一些异常请帮助我 代码:

    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 个答案:

答案 0 :(得分:1)

以这种方式尝试:

    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;
   }

并在onCreate()之外粘贴:

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(); 
} 
}
我认为以这种方式可能会解决你的问题。