SharedPreference
只是一个文件,您可以保存和检索值。这里有您的活动使用SharedPreference
最简单的步骤:
你需要做一个变量sP
这将在SharedPreferences
文件指向你将使用:
SharedPreferences sP = getSharedPreferences("MyPrefs", MODE_PRIVATE);
你需要做一个变量sPeD
其将在“编辑”该文件指出,这将让你把值到该文件:
SharedPreferences.Editor sPeD = sP.edit();
然后,您可以从文件中提取存储的值。该值通过“钥匙”这仅仅是一个String
您定义的索引:
String myString = sP.getString("keyTextYouDefine", "Oops!");
如果没有存储在关键"keyTextYouDefine"
值,那么getString()
会让myString
等于"Oops!"
。
为了存储在该键的值,使用:
sPeD.putString("keyYouDefine","The string I want to save.");
sPeD.commit();
如果你忘记做commit()
你把东西之后的文件中,那么他们实际上并没有放在那里。
这应该会让你顺利地走上正轨。
后来补充:
然后,您可以用它来确定哪些图像上的按钮。
假设你已经propertly定义你的按钮
Button button = findViewById(R.id.myButton) // or whatever you are actually using
无论从任何然后设置图像,如果有什么是存储在ShardPreference
int which = sP.getInt("WhichImage", 1); // assuming image1 is the "default"
switch (which) {
case 1:
button.setCompoundDrawables(null, @drawable/image1, null, null);
break;
case 2:
button.setCompoundDrawables(null, @drawable/image2, null, null);
break;
default: // no image
}
在别处在您的活动,当你做出决定切换按钮图像到image2:
if (whatever) { // condition for changing to image 2
button.setCompoundDrawables(null, @drawable/image2, null, null);
sP.edit().putInt("WhichImage", 2).commit();
}
我从来没有用过setCompoundDrawables()
我自己,所以你的里程可能会有所不同。
感谢您的回答!但是,我如何使用Sharedpreferences来存储这个“映像更改”? – Varki
请参阅使用添加的信息编辑。 – mwengler
非常感谢!现在完美的作品! :) – Varki