首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android Activity 啟動即彈出 Dialog:onResume 中顯示的正確姿勢

     編輯:程式設計疑難解答

需求:進入 Activity 立即顯示對話框

推薦:onResume 顯示(Activity 可見時)


@Override
protected void onResume() {
    super.onResume();
    if (!isDialogShown) { // 防止重複彈出
        new AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage("內容")
            .setPositiveButton("確定", null)
            .show();
        isDialogShown = true;
    }
}

為什麼不用 onCreate?

  • onCreate 時 View 尚未附加到 Window,Dialog 可能顯示異常或崩潰(BadTokenException)。
  • onStart 也可,但 onResume 確保 Activity 處於**前台可互動狀態**。

參數說明

  • Context:傳 this(Activity 本身)。
  • AlertDialog.Builder:鏈式設定標題、訊息、按鈕。
  • .show():建立並顯示 Dialog,回傳 Dialog 實例可持有引用。

進階:自定義 DialogFragment(支援旋轉保留)


public class MyDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(requireActivity())
            .setTitle("標題")
            .setMessage("訊息")
            .setPositiveButton("確定", null)
            .create();
    }
}

// Activity 中顯示
new MyDialogFragment().show(getSupportFragmentManager(), "MyDialog");

總結

onResume + AlertDialog.Builder 最簡單;需配置變更保留狀態用 DialogFragment。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved