一、在Activity启动后立即弹出PopupWindow
若在Activity的onCreate()方法中直接写弹出PopupWindow方法会报错,因为activity没有完全启动是不能弹出PopupWindow的。
那我们只需要在activity完全启动后再弹出PopupWindow就行了。
第一种方法: 利用Activity的 onWindowFocusChanged()方法
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- // TODO Auto-generated method stub
- super.onWindowFocusChanged(hasFocus);
- if(hasFocus){
- // 弹出PopupWindow的具体代码
-
- }
- }
第二种方法: 利用Handler和Runnable
- private Handler mHandler = new Handler();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mHandler.postDelayed(mRunnable, 500);
- }
- private Runnable mRunnable = new Runnable() {
- public void run() {
- // 弹出PopupWindow的具体代码
- }
- };
方法一(这种方法可以处理popupwindows dimiss的时候一些其他的操作,比如让其他控件的隐藏,消失等):
代码如下popupWindow.setFocusable(false);//focusable要为false(不设置默认的就是False);
//这是Activity 的OnTouchEvent。OnTouchEvent代表的是Activity 获得事件(即为PopupWindow之外)
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
}
return super.onTouchEvent(event);
}
方法二:设置popupWindow参数(这种方法只能让自身消失,不能够提供其他伴随操作,比如让其他控件的隐藏,消失等)
pop = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setOutsideTouchable(true);