应用程序首次启动时应打开对话框窗口。

3
我创建了一个对话框,每次用户打开应用程序时都会打开。由于这可能会让用户感到非常烦恼,因此我希望仅在首次启动应用程序时打开它。
我尝试了以下方法:
public boolean openDialog = true;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (openDialog) {
        launchDialog();
    }
}

private void launchDialog() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);

    // set title
    alertDialogBuilder.setTitle("Your Title");

    // set dialog message
    alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    //don't open Dialog by next launch
                    openDialog = false;

                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
            })
            .setNegativeButton("No",new    DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

感谢帮助
Adrian

你的问题并没有明确你遇到了什么困难。到底是什么让你不能如愿以偿? - 1203_dube
3个回答

3

您可以使用简单的sharedPreferences:

 private SharedPreferences mPrefs;
 private Editor mEditor;

初始化:

 mPrefs  = PreferenceManager.getDefaultSharedPreferences(context);
 mEditor = mPrefs.edit();

那么当对话框首次出现时,保存状态,例如:

mEditor.putBoolean(FIRST_TIME_USED_KEY,true);
mEditor.commit();

当应用程序再次打开时,首先询问对话框是否已经打开:

boolean isUsedBefore = mPrefs.getBoolean(FIRST_TIME_USED_KEY,false);

 if(isUsedBefore==true){
   //do nothing
 }else{
  dialog.show();
  }
应该是一个存储在 strings.xml 中的字符串。

1
有多种方法可以实现这一点。
方法1:使用共享首选项。每当用户第一次打开时,在共享首选项中设置状态,并每次检查是否需要显示对话框。
注意:@Opiatefuchs提到了同样的事情。
方法2:使用数据库。第一次和更新状态。下一次检查数据库是否需要显示对话框。
基本上两种方法的工作方式相似。选择您最喜欢的方法。

0
将openDialog变量设置为静态,以便在类的范围内而不是实例中使用:
public static boolean openDialog = true;

为了获得最佳用户体验,您可以显示对话框:
1. 每个时间间隔(例如:2天)。 2. 每次应用程序运行的次数(每5次)。
您可以将这两个因素组合起来,通过使用共享首选项类保存一些值来实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接