使用 SharedPreferences 只显示一次弹出窗口 [英] Use SharedPreferences to display popup only once

查看:66
本文介绍了使用 SharedPreferences 只显示一次弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Intent 添加联系人后,我的 onActivityForResult 方法中有以下代码.

I have the following code in my onActivityForResult method after I add a contact using an intent.

  if (mySharedPrefs.getBoolean("settingsPopup", false) == false) { //First time

            new AlertDialog.Builder(this)
                    .setTitle("Go to settings? ")
                    .setMessage("POPUP")
                    .setNegativeButton("No", null)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            Intent settingsIntent = new Intent(MainActivity.this, Settings.class);
                            startActivity(settingsIntent);

                        }
                    }).show();

            myEditor = mySharedPrefs.edit();
            myEditor.putBoolean("settingsPopup", true);
            myEditor.commit();

        }

我希望这个弹出窗口只显示一次,这就是我在第一次显示对话框后将共享首选项键值settingsPopup"设置为 true 的原因.但出于某种原因,对话框显示每次onActivityForResult 方法被调用.为什么每次都显示?

I want this popup to only show once, which is why I set the shared preference key value "settingsPopup" to true after I first show the dialog. For some reason though, the dialog shows every time the onActivityForResult method gets called. Why does it show every time?

PS:我使用相同的共享首选项对象来存储其他值.

PS: I am using the same shared preference object for storing other values.

我在 onCreate 中初始化我的共享首选项,如下所示:

I initialize my shared prefs in onCreate like so:

mySharedPrefs = this.getSharedPreferences("sharedPrefsName", MainActivity.MODE_PRIVATE);//制作共享偏好

推荐答案

创建一个类并调用它SettingManager,如下所示:

Create a class and call it SettingManager like following :

public class SettingsManager {
    public static final String DEFAULT_PREFERENCES_NAME = "defaultPreferences";

    public static final String PREFERENCE_FIRST_RUN = "isFirstRun";

    public static SharedPreferences getDefaultPreferences(Context context) {
        return context.getSharedPreferences(DEFAULT_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    public static boolean isFirstRun(Context context) {
        SharedPreferences preferences = getDefaultPreferences(context);
        boolean isFirstRun = preferences.getBoolean(PREFERENCE_FIRST_RUN, true);
        preferences.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();

        return isFirstRun;
    }

}

然后像这样调用它:

boolean isFirstRun = SettingManager.isFirstRun(getActivity());

这篇关于使用 SharedPreferences 只显示一次弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆