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);