Displaying alerts in Activity.onCreate(..)

后端 未结 3 1840
天命终不由人
天命终不由人 2021-02-08 01:04

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 Al

相关标签:
3条回答
  • 2021-02-08 01:37

    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();
    }
    
    0 讨论(0)
  • 2021-02-08 01:50

    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
    }
    
    0 讨论(0)
  • 2021-02-08 01:59

    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 i.e.

    public void onPause()
    {
    super.onPause();
    if(alert !=null)
    {
    alert.dismiss();
    }
    }
    
    0 讨论(0)
提交回复
热议问题