禁用弹出窗口的后退按钮

时间:2016-04-05 16:20:45

标签: android api popupwindow viewgroup onbackpressed

根据教授如何创建弹出窗口的YouTube教程视频(https://www.youtube.com/watch?v=wxqgtEewdfo),我想知道如何使用触摸事件而不是后退按钮来关闭弹出窗口。 ..

这是MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RelativeLayout relative = (RelativeLayout)findViewById(R.id.relativeTest);

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().
                    getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.myLayout, null);

            PopupWindow popupWindow = new PopupWindow(container, AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.MATCH_PARENT, true);
            popupWindow.showAtLocation(relative, Gravity.CENTER, 0, 0);

            container.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    popupWindow.dismiss();

                    return true;
                }
            });
        }
    });
}

@Override
public void onBackPressed() {
    // I want the back button to be disabled for both MainActivity and the
    // popup window.
}

...我应该将onBackPressed()置于其他地方,还是可能的?

提前致谢。

3 个答案:

答案 0 :(得分:0)

将onBackPressed留空。删除super.OnBackPressed行

答案 1 :(得分:0)

试试这个: -

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
        && keyCode == KeyEvent.KEYCODE_BACK) {
    Log.d("CDA", "onKeyDown Called");
    onBackPressed();
    return true; 
}
return super.onKeyDown(keyCode, event);
}

答案 2 :(得分:0)

好的,我现在想出来了(归功于Filip,YouTube视频的上传者)...问题在于我将PopupWindow的最后一个参数设置为true,并将其设置为true,并且我得到了摆脱它如下:

popupWindow = new PopupWindow(container, AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.MATCH_PARENT);

...弹出窗口现在只能通过触摸事件解除。