在开发中一般会使用到PopupWindow,使用时有时我们会需要对返回键监听来实现自己的需求,但是在使用时总会出现问题
这是我在网上搜索到的方法但是并没有效果
View view = View.inflate(mctx, R.layout.pop_file_upload, null);
final PopupWindow pop = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
pop.setOutsideTouchable(true);
pop.setFocusable(true);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
ColorDrawable dw = new ColorDrawable(mctx.getResources().getColor(R.color.pop));
pop.setBackgroundDrawable(dw);
pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
pop.getContentView().setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d(TAG, "onKey: +++++++++++++"+9999);
agentWeb.back();
pop.dismiss();
return true;
}
Log.d(TAG, "onKey: 6666"+888);
return false;
}
});
经过查看源码发下。在该方法pop.setBackgroundDrawable里当背景不为null时他会自己创建一个PopupDecorView
这个popDecorView继承自fragmentLayout,在里面他已经吧返回键监听过了,所以不管用了。所以为了监听返回键我把背景设置在了view里,在setBackgroundDrawable方法里设置为null,就行了。