在 Activity 创建后 3 秒和最后 3 秒显示 PopupWindow

Show PopupWindow 3 seconds after Activity is created and last 3 seconds

我在 activity 中有弹出窗口 window。我想要的是此弹出窗口在创建 activity 3 秒后开始并持续 3 秒。有什么帮助吗?

这是我的代码:

try {
    LayoutInflater inflater1 = (LayoutInflater) MainActivity.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // Inflate the view from a predefined XML layout
    View layout = inflater1.inflate(R.layout.activity_pop_up,
            (ViewGroup) findViewById(R.id.relativeLayoutZaFragment));
    // create a 300px width and 470px height PopupWindow
    pw = new PopupWindow(layout, 300, 470, true);
    // display the popup in the center
    pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
} catch (Exception e) {
    e.printStackTrace();
}

试试这个

boolean isShowing=false;

在onCreate

    CountDownTimer timer=new CountDownTimer(3000,1000) {
        @Override
        public void onTick(long l) {

        }

        @Override
        public void onFinish() {
            if(isShowing){
                //CLOSE
            }
            else{
            isShowing=true;
            LayoutInflater inflater1 = (LayoutInflater)
                    MainActivity.this
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //Inflate the view from a predefined XML layout
            View layout = inflater1.inflate(R.layout.activity_pop_up,
                    (ViewGroup) findViewById(R.id.relativeLayoutZaFragment));
            // create a 300px width and 470px height PopupWindow
            pw = new PopupWindow(layout, 300, 470, true);
            // display the popup in the center
            pw.showAtLocation(layout, Gravity.CENTER, 0, 0)
            timer.start();
            }
        }
    };
    timer.start();

这可以通过在 Handler 上发布活动轻松实现。

private final Handler handler = new Handler(Looper.getMainLooper());
private PopupWindow popupWindow;

private final Runnable dismissPopupRunnable = new Runnable() {
    @Override
    public void run() {
        // dismiss popupWindow
    }
};

private final Runnable showPopupRunnable = new Runnable() {
    @Override
    public void run() {
        // show popupWindow
        handler.postDelayed(dismissPopupRunnable, 3000);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // initialize popupWindow here

    handler.postDelayed(showPopupRunnable, 3000);
}

@Override
protected void onPause() {
    super.onPause();
    handler.removeCallbacks(showPopupRunnable);
    handler.removeCallbacks(dismissPopupRunnable);
}

注意,当 activity 暂停时,您必须注意从处理程序中删除回调。