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

之前在网上找了很多文章,实现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() {
	@Override
	public void onClick(View v) {
		dismissPopupWindow();
	}
});
popupView.setFocusable(true);
popupView.setFocusableInTouchMode(true);
popupView.setOnKeyListener(new View.OnKeyListener() {
	@Override
	public 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()里做你想要的动作。






你可能感兴趣的:(Android)