简体   繁体   中英

Displaying alerts in Activity.onCreate(..)

I am new to Android and this is my first question here so please go easy on me.

Is it possible to check some condition inside onCreate() of an Activity and display an AlertDialog?

I am creating an AlertDialog anonymously in Oncreate() and calling show on that instance but the AlertDialog is never displayed.

Showing an alert dialog in onCreate causes android.view.WindowLeaked exception, because the activity isn't yet created.

The solution I found is to put the code that shows the dialog in onStart() method:

@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. Also ensure that you create the onPause method in your activity to dismiss the alert ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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