在此是另外建立一個獨立的SharedPreferences, 讓其它class可以讀取
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; public class SystemPreference { protected static SharedPreferences settings; protected static SharedPreferences.Editor editor; protected static SharedPreferences settingsForStatus; protected static SharedPreferences.Editor editorForStatus; static int lastPosition; public static void registerForStatusOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener){ if(settingsForStatus !=null){ settingsForStatus.registerOnSharedPreferenceChangeListener(listener); } } public static void unregisterForStatusOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener){ if(settingsForStatus !=null){ settingsForStatus.unregisterOnSharedPreferenceChangeListener(listener); } } public static void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener){ if(settings !=null){ settings.registerOnSharedPreferenceChangeListener(listener); } } public static void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener){ if(settings !=null){ settings.unregisterOnSharedPreferenceChangeListener(listener); } } public static int getLastPosition(){ //取出name屬性的字串 lastPosition = settingsForStatus.getInt("LastPosition", 0); if(lastPosition == 0){ return 0; }else{ return lastPosition; } } public static void setLastPosition(int lastPosition){ //置入name屬性的字串 settingsForStatus.edit().putInt("LastPosition", lastPosition).commit(); } /** * Load the plugin preferences */ public static boolean load(Context a) { try { if (settingsForStatus == null) { settingsForStatus = a.getSharedPreferences("Preference", 0); editorForStatus = settingsForStatus.edit(); } return true; } catch (Exception e) { } return false; } }在其它class onCreate時註冊
@Override public void onCreate(Bundle savedInstanceState) { SystemPreference.registerForStatusOnSharedPreferenceChangeListener(this); SystemPreference.load(context); }在離開時記得反註冊以免佔用資源
@Override protected void onStop() { super.onStop(); SystemPreference.unregisterForStatusOnSharedPreferenceChangeListener(this); }之後在需要使用的地方直接呼叫就行
SystemPreference.setLastPosition(傳入整數); SystemPreference.getLastPosition();
沒有留言:
張貼留言