在 activity 上显示弹出窗口创建失败

Show pop up on activity create fails

我正在尝试在 activity on create() 方法上显示 popup,但似乎什么也没有发生.. 没有 exception 没有 popup.

代码如下

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    btnClear = (Button)findViewById(R.id.btnClear);
    txtPassword = (TextView) findViewById(R.id.txtPassword);
    txtPassword.setOnTouchListener(otl);
    btnClear.setVisibility(View.GONE);
    objDBHelper = DBHelper.getInstance(getApplicationContext());
    SQLiteDatabase db = objDBHelper.getWritableDatabase();
    long driverProfileCount = objDBHelper.getProfilesCount(db);

        initiatePasswordPopupWindow(); // show pop up when no data is in table

}

 private void initiatePasswordPopupWindow() {
    try {
        //We need to get the instance of the LayoutInflater, use the context of this activity
        LayoutInflater inflater = (LayoutInflater) Login.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //Inflate the view from a predefined XML layout
      final  View layout = inflater.inflate(R.layout.setting_password_popup,
                (ViewGroup) findViewById(R.id.setting_password_popup_element));
        // create a 300px width and 470px height PopupWindow
        pw = new PopupWindow(layout, 600, 720, true);
        // display the popup in the center
        layout.post(new Runnable() {
            public void run() {
                pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
                Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
                cancelButton.setOnClickListener(cancel_button_click_listener);
            }
        });

       /* TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);*/


    } catch (Exception e) {
        e.printStackTrace();
    }
}

我错过了什么?

您尝试将 post 与未启动其消息队列的视图(PopupWindow 布局)一起使用。尝试使用 activity 中已有的视图,例如根视图 - 将 layout.post(new Runnable() { 更改为 findViewById(android.R.id.content):

findViewById(android.R.id.content).post(new Runnable() {
    public void run() {
        pw.showAtLocation(layout, Gravity.CENTER, 0, 0);

        Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
        cancelButton.setOnClickListener(cancel_button_click_listener);
    }
});