private void showPopupWindow() {
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);
PopupWindow mPopWindow = new PopupWindow(contentView);
//充满全屏
mPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mPopWindow.setHeight(ViewGroup.LayoutParams.<span style="font-family: Arial, Helvetica, sans-serif;">MATCH_PARENT</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span>
<span style="white-space:pre"> </span>//另一种使布局充满全屏的方法
// mPopWindow.setHeight(getWindowManager().getDefaultDisplay().getHeight());
// mPopWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth());
//是否响应touch事件
mPopWindow.setTouchable(true);
//是否具有获取焦点的能力
mPopWindow.setFocusable(true);
//外部是否可以点击
mPopWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
mPopWindow.setOutsideTouchable(true);
mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
mPopWindow.showAsDropDown(mMenuTv);//展示在哪个view下面
}
以上是popuwindow在android6.0以下,屏蔽返回键起作用;但在android6.0以上,仍然可以按返回键使得popuwindow消失;
下面是适配6.0以下的:
private void initPopuwindow() {
popupWindowView = View.inflate(VideoLiveActivity.this, R.layout.video_live, null);
viewHolder = new ViewHolder(popupWindowView);
popupWindow = setPopupwindow(popupWindowView);
}
private PopupWindow setPopupwindow(View view) {
PopupWindow mPopWindow = new PopupWindow(view);
final DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mPopWindow.setWidth(metrics.widthPixels);
mPopWindow.setHeight(metrics.heightPixels);
//是否响应touch事件
mPopWindow.setTouchable(true);
//是否具有获取焦点的能力
mPopWindow.getContentView().setFocusable(true);
mPopWindow.getContentView().setFocusableInTouchMode(true);
//在Android 6.0以下使用
mPopWindow.setOutsideTouchable(false);
//在Android 6.0以上 ,只能通过拦截事件来解决
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mPopWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
if ((event.getAction() == MotionEvent.ACTION_DOWN)
&& ((x < 0) || (x >= metrics.widthPixels) || (y < 0) || (y >= metrics.heightPixels))) {
return true;
} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
return true;
}
return false;
}
});
}
return mPopWindow;
}
第一个方法是初始化popuwindow,第二个是构建popuwindow对象。