我会按照列尼克所说的去做,但不要让它们成为静态的,而是懒惰地初始化它们。
public class MyApplication extends Application {
public SharedPreferences preferences;
public SharedPreferences getSharedPrefs(){
if(preferences == null){
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
}
return preferences;
}
那么在你看来:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
正如 eric 所说,这个 Application 类需要在你的清单中声明:
<application android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
参考:
获取应用程序上下文()
Android 全局变量
编辑
(根据您的评论)问题是您实际上并没有保存任何数据,这一行没有意义,您实际上并没有保存变量:
editor.putString("Data", (Data));
以下是上述使用的示例:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
String str = settings.getString("YourKey", null);
并将某些内容保存到首选项中:
settings.edit().putString("YourKey", "valueToSave").commit();
在自定义视图中使用的更具体示例是:
public class MyView extends View {
SharedPreferences settings;
// Other constructors that you may use also need the init() method
public MyView(Context context){
super(context);
init();
}
private void init(){
MyApplication app = (MyApplication) getContext().getApplicationContext();
settings = app.getSharedPrefs();
}
private void someMethod(){ // or onTouch() etc
settings.edit().putString("YourKey", "valueToSave").commit(); //Save your data
}
private void someOtherMethod(){
String str = settings.getString("YourKey", null); //Retrieve your data
}
}