android的popupwindow点击返回按钮关闭

今天想实现点击Popupwindow的外边不消失,点击返回键popupwindow自动关闭的效果,网上找了找,发现没有完整的,零碎的而且不准确,于是自己琢磨了一下,试了试效果。以下是实现效果的代码

View keyboardView = LayoutInflater.from(activity).inflate(R.layout.random_keyboard, null); 
 popupWindow = new PopupWindow(keyboardView,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,false);
//设置点击窗口外边窗口消失 
 popupWindow.setOutsideTouchable(false); 
   // 设置此参数获得焦点,否则无法点击 
 popupWindow.setFocusable(true);
 
// popupWindow.setBackgroundDrawable(new BitmapDrawable());  //comment by danielinbiti,如果添加了这行,那么标注1和标注2那两行不用加,加上这行的效果是点popupwindow的外边也能关闭
 keyboardView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件,标注1
 keyboardView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
 keyboardView.setOnKeyListener(new OnKeyListener(){
	@Override
	public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
     		if (arg1 == KeyEvent.KEYCODE_BACK){
      		if(popupWindow != null) {
      			close();
     			} 
     		}
     		 return false; 
	}
 });


你可能感兴趣的:(android,消失,PopupWindow,返回键)