PopupWindow的显示

public class MyPopupWindow{
	private final String TAG = "MyPopupWindow";
	private Context mContext;
	private View parent;
	private PopupWindow mWindow;
	
	private LinearLayout rootView;
	
	//view可以不设置
	public MyPopupWindow(Context context, View view) {
		this.mContext = context;
		this.parent = view;
		initPopupWindow();
	}

	private void initPopupWindow(){
		this.rootView = (LinearLayout)((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.share_window, null);
		//WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		//int width = wm.getDefaultDisplay().getWidth();
		//Log.e(TAG, "window size=" + w + "*" + h);
		
		mWindow = new PopupWindow(rootView);
        mWindow.setFocusable(false);
        mWindow.setBackgroundDrawable(new BitmapDrawable()); //为null是点击外部无反应
        mWindow.setOutsideTouchable(true);//设置setBackgroundDrawable后且为true时点击外部才有反应
        mWindow.setWindowLayoutMode(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);//由布局控制高度
	}
	public void showMyPopupWindow(){
		rootView.post(new Runnable() {//直接在onCreate中调用显示报错
			@Override
			public void run() {
				try {
					if(parent == null){
						mWindow.showAtLocation(rootView, Gravity.BOTTOM, 50, 0);
					}else{
						mWindow.showAtLocation(parent, Gravity.BOTTOM, 50, 0);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
	}
	
	public void hideMyPopupWindow(){
		if(mWindow != null){
			mWindow.dismiss();
		}
	}
	
	}


注意点:

(1)android.view.WindowManager$BadTokenException: Unable to add window错误

android.view.WindowManager$BadTokenException: Unable to add window --token null is not valid; is your activity running?

最后终于发现是PopupWindow组件的使用问题,如果你直接在Activity创建的方法中初始化,则会有此错误

因此总结:PopupWindow必须在某个事件中显示或者是开启一个新线程去调用,不能直在oncreate方法中显示一个PopupWindow,否则永远会有以上错误。可通过view的post显示。

(2)去除黑色背景边

ColorDrawable dw = new ColorDrawable(0x00000000);//去除背景黑色
mWindow.setBackgroundDrawable(dw);

(3)再次点击触发view(点击时显示PopupWindow的view),隐藏popupwindow,需要设置mWindow.setFocusable(true);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值