Android popupWindow取消响应back按钮

来源:互联网 发布:在线建立数据库 编辑:程序博客网 时间:2024/05/16 06:46

    想实现的效果是,点击返回按钮,popwindow不隐藏。遇到很多问题,PopupWindow 跟我们的 Activity 不一样,因为我们在构造 PW 的时候往往不是继承来的,而是 new 出来的。所以不能使用重写 PW 的 onKeyDown() 之类的方法来截获键盘事件。

    试了两种方法:

    首先在 PW 的布局文件(*.xml)中随意选取一个不影响任何操作的 View,推荐使用最外层的 Layout。
然后设置该 Layout 的 Focusable 和 FocusableInTouchMode 都为 true。
接着回到代码中,获取该 View 的实例,现在你就可以对该 View 重写 OnKeyListener() 事件了。
我们可以手动捕获 KEYCODE_BACK 给对话框 dismiss()。
给出一段示例:

PopupWindow pw;
View view;
RelativeLayout layMenu;

LayoutInflater inflater = (LayoutInflater) cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.loading_popwindow_layout, null, false);
layMenu = (RelativeLayout) view.findViewById(R.id.loading_relative_layout);

int w = ((Activity) cxt).getWindowManager().getDefaultDisplay().getWidth();
int h = ((Activity) cxt).getWindowManager().getDefaultDisplay().getHeight();

pw =new PopupWindow(view, w, h,true);


loading_relative_layout = (RelativeLayout) view.findViewById(R.id.loading_relative_layout);


loading_popwindow_image = (ImageView) view.findViewById(R.id.loading_popwindow_image);
loading_popwindow_tip = (TextView) view.findViewById(R.id.loading_popwindow_tip);


operatingAnim = new RotateAnim(0, 359, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);


operatingAnim.setRepeatCount(-1);
operatingAnim.setDuration(3000);
LinearInterpolator lin = new LinearInterpolator();
operatingAnim.setInterpolator(lin);
if (null != operatingAnim) {
loading_popwindow_image.startAnimation(operatingAnim);
}


layMenu.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
return false;
}
});

return pw;


这个返回的pw就能够拦截back事件,需要注意的是不能设置popWindow的背景,让其默认为null!!!

0 0
原创粉丝点击