Android PopupWindow响应返回键最正确的实现方式

来源:互联网 发布:ubuntu虚拟机分区 编辑:程序博客网 时间:2024/06/07 20:23

之前在网上找了很多文章,实现PopupWindow返回键的方式如下:

popupWindow.setFocusable(true);ColorDrawable dw = new ColorDrawable(0x00000000);popupWindow.setBackgroundDrawable(dw);

这样是实现了点击返回键关闭PopupWindow。但是,我们没办法在PopupWindow关闭时做其他你想要的操作。


正确的方法是:

popupView = getLayoutInflater().inflate(R.layout.detail_popupwindow, null);popupView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {dismissPopupWindow();}});popupView.setFocusable(true);popupView.setFocusableInTouchMode(true);popupView.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {dismissPopupWindow();return true;}return false;}});if (popupWindow == null) {popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);popupWindow.setFocusable(true);}if (!popupWindow.isShowing())popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

你可以在dismissPopupWindow()里做你想要的动作。






0 0
原创粉丝点击