android - AlertDialog 不会显示在 onCreate 方法中

标签 android dialog oncreate

所以我想在继续构建 Activity 之前询问用户他们的名字。大多数 Activity 都是动态填充的,所以看起来这应该很容易。出于某种原因,对话框从未出现过。我什么都试过了,我唯一能想到的是:也许它不喜欢在 onCreate 方法中?但这似乎不是问题,因为它实际上是 onCreate 中调用的最后一个方法。检查一下,让我知道您看到了什么:

onCreate 方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initializeHotels();
    FIRST_TURN = true;

    clearOldBoard();
    setContentView(R.layout.activity_game_board);
    setUpBoardGUI();

    setOnPlayerSetUpEventListener(new onPlayerSetUpEventListener() {
        @Override
        public void onPlayerSetUp(){
            prepForFirstTurn();
        }
    }); 

    startGameDialog();
}

和 startGameDialog 方法:

public void startGameDialog(){
    Context context = getApplicationContext();

    ContextThemeWrapper ctw = new ContextThemeWrapper(context, R.style.AppBaseTheme);

    AlertDialog.Builder startGameDialog = new AlertDialog.Builder(ctw);
    startGameDialog.setTitle(getResources().getString(R.string.whats_your_name));

    LinearLayout dialogLayout = new LinearLayout(context);

        final EditText newName = new EditText(context);
        newName.setText("");

        Button submit = new Button(context);
        OnClickListener onClick = new OnClickListener() {

            @Override
            public void onClick(View v) {
                GameBoardActivity.NAME = newName.toString();
                setUpPlayers();

            }
        };
        submit.setOnClickListener(onClick);

    dialogLayout.addView(newName);
    dialogLayout.addView(submit);

    startGameDialog.setView(dialogLayout);
    Dialog dialog = startGameDialog.create();
    dialog.show();
    dialog.setCancelable(false);

}

最佳答案

create 方法返回 AlertDialog 的一个实例

而不是在调用AlertDialog的create方法时将其初始化为Dialog

Dialog dialog = startGameDialog.create();
dialog.show();

传递给AlertDialog

AlertDialog alertDialog = startGameDialog.create();
alertDialog.show();

使用当前 Activity 上下文而不是使用整个应用程序上下文。t

Context context = Your_activity.this;

关于android - AlertDialog 不会显示在 onCreate 方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24174996/

相关文章:

Android Application Init 和全局对象

dialog - Electron dial.showOpenDialog 未运行回调

Android:onCreate() 被多次调用(不是我调用的)

Java onCreate 带有参数,如 initWithParameter c++

android - 为什么 OnCreate 应该在 Activity 启动时只调用一次?

android - Android 中的处理程序和内存泄漏

android - API 17 - Android 通知在不被点击的情况下启动 Activity

android - 使 TextView 在 Android 上可滚动

jQuery UI 对话框边框在 1.12.1 中不再工作

javascript - 在模态对话中打开完整的 html(带有 head、css 等)