Displaying alerts in Activity.onCreate(..)

ⅰ亾dé卋堺 提交于 2019-12-12 07:46:30

问题


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.


回答1:


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
}



回答2:


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();
}



回答3:


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();
}
}


来源:https://stackoverflow.com/questions/3509391/displaying-alerts-in-activity-oncreate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!