Android中在onCreate()时弹出popwindow,很多人都有过类似的需求吧,但是直接在onCreate()中调用popwindow的showAtLocation()方法是会报异常的,原因是此时activity还没有初始化完毕,网上也有一些解决方法,但一般都是通过延时一小段时间再弹出实现的,代码不够健壮。其实可以通过不断的检测当前activity的状态,一旦初始化完毕立即调用popwindow的showAtLocation()方法显示。详细代码如下:
-
- package cn.sd.sx.initpopw;
-
- import android.app.Activity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.os.Handler;
- import android.view.Gravity;
- import android.view.View;
- import android.view.ViewGroup.LayoutParams;
- import android.widget.LinearLayout;
- import android.widget.PopupWindow;
- import android.widget.TextView;
- import cn.sd.sx.popw.R;
-
- public class PopWActivity extends Activity {
-
- private PopupWindow mPopupWindow;
- private Handler mHandler;
-
- private int detchTime = 5;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mHandler = new Handler();
-
- showPopWindow();
- }
-
- private void showPopWindow()
- {
- LinearLayout view = new LinearLayout(this);
- LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
- LayoutParams.FILL_PARENT);
- TextView txt1 = new TextView(this);
- txt1.setLayoutParams(params);
- txt1.setGravity(Gravity.CENTER);
- txt1.setText("txt1");
- txt1.setBackgroundColor(Color.RED);
- view.addView(txt1);
- mPopupWindow = new PopupWindow(view, 300,300);
- mPopupWindow.setOutsideTouchable(true);
-
-
- Runnable showPopWindowRunnable = new Runnable() {
-
- @Override
- public void run() {
-
- View view = findViewById(R.id.main);
-
- if( view != null && view.getWidth() > 0 && view.getHeight() > 0) {
-
- mPopupWindow.showAtLocation(PopWActivity.this.findViewById(R.id.main),
- Gravity.CENTER, 0, 0);
-
- mHandler.removeCallbacks(this);
- } else {
-
- mHandler.postDelayed(this, detchTime);
- }
- }
- };
-
- mHandler.post(showPopWindowRunnable);
-
- }
- }