0

有没有办法让警报只在应用程序打开时出现?我在 MainActivity 的 onStart() 中创建了一个警报,每当我回到应用程序中的那个活动时,它都会再次显示警报,这可能会让用户感到烦恼。或者有没有办法创建一个“得到它”按钮然后关闭警报?这是我的代码:

protected void onStart() {
    super.onStart();
    new AlertDialog.Builder(this)
            .setTitle("Instructions")
            .setMessage("Hello! To begin, select a map from the list to train with. Make sure" +
                    " you are on the correct floor.")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(R.drawable.ic_launcher)
            .show();

}
4

2 回答 2

1

这是因为当另一个活动出现在您的前台时,您 MainActivity 的活动会转到OnPause(). 然后当你回到你的 MainActivity 时。系统再次调用 onStart()请参阅活动生命周期

-第一个解决方案

public class TestActivity extends ActionBarActivity {

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

    if (savedInstanceState == null) {
        showAlertDialog();
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

}

-第二种解决方案

public class TestActivity extends ActionBarActivity {

private static boolean isAlertDialogShownBefore = false;

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

    if (!isAlertDialogShownBefore) {
        showAlertDialog();
        isAlertDialogShownBefore = true;
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

@Override
public void onBackPressed() {
    isAlertDialogShownBefore = false;
    super.onBackPressed();
}

}

于 2015-06-12T17:04:10.527 回答
0

将该代码放入活动的 onCreate 方法中。检查 saveInstanceState 是否为 null,如果是则显示您的 alertDialog

于 2015-06-12T17:00:14.067 回答