很抱歉,如果在re是任何語法或編譯問題,只是輸入我的頭腦,可能會犯一些錯誤。因此,本質上這是一種方法,您可以使用它從一個簡單的類公開您的前綴並從任何地方訪問它。
public class MySharedPrefs {
public SharedPreferences sp;
public MySharedPrefs()
{
this.sp = c.getSharedPreferences("prefs", Context.MODE_PRIVATE);
}
public static String getStringFieldValue(Context c, String fieldName)
{
MySharedPrefs p = new MySharedPrefs(c);
return p.sp.getString(fieldName, "default value");
}
public static void setStringValue(Context c, String fieldName, String value)
{
MySharedPrefs p = new MySharedPrefs(c);
SharedPreferences.Editor edit;
edit = p.sp.edit();
edit.putString(fieldName, value);
edit.commit();
}
}
然後在你的活動中使用這樣的:
MySharedPrefs.getStringFieldValue(this, "name");
您可以也擴大這一類,並添加額外的helper方法,如getUserName
或等
UPDATE:
當從另一個靜態類調用此類時,該類需要引用您的應用程序上下文,然後您需要爲此fu提供該上下文而不是使用這個。
MySharedPrefs.getStringFieldValue(context, "name"); //if your other static class has a property called context that contains your applications context
仍不清楚與問題 – KOTIOS