标签:
今天在练习PopupWindow弹出框的时候,打算在界面加载的时候将弹出框展现出来并显示在指定的view下面。
初步方法是直接在OnResume方法里面直接执行showPopupWindows方法。
但是报“Unable to add window -- token null is not valid; is your activity running?”
原因参考:http://cb269267.iteye.com/blog/1787779
总结下原因如下:popupwindow必须要指定一个view,如果这个view还没有创建显示出来,那么就会报这种错误。
解决思路是:延迟一段时间再执行showPopupWindows方法。上面的链接里面就是这个思路。
方法一:直接使用Handle延迟
public void onResume() { super.onResume(); //方式一:直接使用Handle延迟 Message msg = popHandler.obtainMessage(); msg.what = 0; msg.arg1 = 0; msg.obj = toptab_Items.get(0); popHandler.sendMessageDelayed(msg, 500); }
private Handler popHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: View view = (View) msg.obj; int index = msg.arg1; showPopupWindows(view,index); popHandler.removeCallbacks(runnable); break; default: break; } } };
方法二:通过子线程延迟
public void onResume() { super.onResume(); //方式二:子线程延迟 popHandler.post(runnable); }
private Handler popHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: View view = (View) msg.obj; int index = msg.arg1; showPopupWindows(view,index); if(timer != null){ timer.cancel(); } popHandler.removeCallbacks(runnable); break; default: break; } } };
private Timer timer; //创建一个子线程 private Runnable runnable = new Runnable() { public void run() { try { timer = new Timer(); TimerTask task = new TimerTask() { public void run() { Message msg = popHandler.obtainMessage(); msg.what = 0; msg.arg1 = 0; msg.obj = toptab_Items.get(0); popHandler.sendMessage(msg); } }; timer.schedule(task, 500); } catch (Exception e) { // TODO: handle exception } } };
备注:
/**显示popupWindow弹出框在指定的view下面*/
private void showPopupWindows(View view, int index){。。。。}
练习PopupWindow弹出框之实现界面加载的时候显示弹出框到指定的view下面--两种延迟方法
标签:
原文地址:http://www.cnblogs.com/whycxb/p/4802787.html