简体   繁体   English

在Activity.onCreate(..)中显示警报

[英]Displaying alerts in Activity.onCreate(..)

I am new to Android and this is my first question here so please go easy on me. 我是Android新手,这是我在这里的第一个问题,所以请放轻松我。

Is it possible to check some condition inside onCreate() of an Activity and display an AlertDialog? 是否可以检查Activity的onCreate()内的某些条件并显示AlertDialog?

I am creating an AlertDialog anonymously in Oncreate() and calling show on that instance but the AlertDialog is never displayed. 我在Oncreate()中匿名创建一个AlertDialog并在该实例上调用show但从不显示AlertDialog。

Showing an alert dialog in onCreate causes android.view.WindowLeaked exception, because the activity isn't yet created. 在onCreate中显示警告对话框会导致android.view.WindowLeaked异常,因为尚未创建活动。

The solution I found is to put the code that shows the dialog in onStart() method: 我找到的解决方案是将显示对话框的代码放在onStart()方法中:

@Override
protected void onStart() {
    super.onStart();
    // show dialog here
}

It is definitely possible, try this: 绝对有可能,试试这个:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Stackoverflow!").create().show();
}

If using ActivityGroups then you need to use getParent() instead of the keyword this. 如果使用ActivityGroups,则需要使用getParent()而不是关键字this。 Also ensure that you create the onPause method in your activity to dismiss the alert ie 还要确保在活动中创建onPause方法以关闭警报,即

public void onPause()
{
super.onPause();
if(alert !=null)
{
alert.dismiss();
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM