android - (新手)有人可以给我一个 Activity 级别偏好的例子吗?

标签 android android-activity

好的,这就是我完成“共享首选项”示例的方式,它在我的助手首选项类中:

public static final String GAME_PREFERENCES = "GamePrefs";

这是我的 Activity 类(class)之一:

     SharedPreferences settings = 
         getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE); 
         SharedPreferences.Editor prefEditor = settings.edit(); 
         prefEditor.putString("lastLaunch", returnTimeAndDateFormatted()); 
         prefEditor.commit();


         SharedPreferences settings2 = 
             getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
             if (settings2.contains("lastLaunch") == true) { 
//               System.err.println(settings2.getString("lastLaunch", "Default"));
                 Log.i("LASTLAUNCH", settings2.getString("lastLaunch", "Not LastLaunch value found!"));
             }

据我所知,我可以从我的任何 Activity 类中访问变量“lastLaunch”,这一切都很好而且很漂亮。

我的书上说还有一种叫做“Activity 级别偏好”的东西,但没有给出例子:(

有人可以给我一个例子(代码)吗?

提前致谢!

最佳答案

一个例子是使用 getPreferences() Activity 方法。

SharedPreferences settings = getPreferences(MODE_PRIVATE); 
SharedPreferences.Editor prefEditor = settings.edit(); 
prefEditor.putString("lastLaunch", returnTimeAndDateFormatted()); 
prefEditor.commit();

SharedPreferences settings2 = getPreferences(MODE_PRIVATE);
if (settings2.contains("lastLaunch") == true) { 
    Log.i("LASTLAUNCH", settings2.getString("lastLaunch", "Not LastLaunch value found!"));
}

这里 lastLaunch 是这个 Activity 私有(private)的。

关于android - (新手)有人可以给我一个 Activity 级别偏好的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5175004/

相关文章:

android - 我真的需要加密数据吗?

android - 如何在 android 上为发布和调试配置应用程序检查?

android - 当编辑文本获得焦点时滚动页面

java - 如何以编程方式动态创建所有 Android ui 组件的列表?例如 TextView 、 ImageView 等

Android:从 Intent Activity 返回主 Activity 后执行方法

android - 如何用手指移动 OpenGL 正方形?

android - 如何让Plantuml为Android Studio中的现有项目渲染uml?

java - 如何从另一个 Activity 发送/检测对特定 Activity 的引用/标记

android - 启动 Activity 不会将应用程序置于前台

android - 如何在不同的 Activity 中使用相同的 LinearLayout