【发布时间】:2012-03-06 04:20:26
【问题描述】:
我正在制作一个使用 int 设置应用程序背景的设置屏幕。它工作得很好......在当前活动中。但是一旦我离开活动,int 值就会丢失并且背景不会改变。
我想做什么:我想从我的设置活动中保存 int,然后将其导入我的其他活动并检查 int "bak" 是否等于 null、"bg"、 “bg1”或“bg2”。
我听说过 sharedPreferences,但从来没有用过。这就是为什么我打开一个新线程。
【问题讨论】:
我正在制作一个使用 int 设置应用程序背景的设置屏幕。它工作得很好......在当前活动中。但是一旦我离开活动,int 值就会丢失并且背景不会改变。
我想做什么:我想从我的设置活动中保存 int,然后将其导入我的其他活动并检查 int "bak" 是否等于 null、"bg"、 “bg1”或“bg2”。
我听说过 sharedPreferences,但从来没有用过。这就是为什么我打开一个新线程。
【问题讨论】:
好的,添加这些全局变量
SharedPreferences data;
public static String filename = "whateveryou want";
在 onCreate 中初始化
data = getSharedPreferences(filename, 0);
然后添加一些东西,使用它,"key" 是一个唯一的描述符,name 是你要存储的变量名
SharedPreferences.Editor editor = data.edit();
editor.putInt("key", name);
editor.commit();
通过这个访问它,如果不存在首选项,default 是您希望分配的变量。
intVariable = data.getInt("key", default);
编辑:
我注意到您想使用字母,例如 bg1 等。为此,您需要使用字符串,或者使用带有 switch case 或多个 if 语句的 int。这是您可以修改的开关案例示例。只需确保将 switch case 语句放在在您访问上一个代码块中的 SharedPreference 之后。
switch (integerVariable){
case 1: // if the intagerVariable = 1, notice the : not a ;
// set background to BG1
break;
case 2: // if the intagerVariable = 2, notice the : not a ;
// set background to BG2
break;
}
只需根据需要添加尽可能多的 case 语句。
【讨论】:
name = getString(key, default)的任何变量