How to change state of a preference item from outside the PreferenceActivity?

笑着哭i 提交于 2019-12-07 05:17:39

问题


There are some features in my app which require android version 4.2+. So in my main activity, i will need to check for available OS features and modify(Enable/Disable)preferences items which are defined in my PreferenceActivity.

The following code is unreachable from outside the PreferenceActivity

ListPreference prefReport = (ListPreference)getPreferenceScreen().findPreference("pref_report");
prefDspProfile.setValue("0");

So my question is how to modify preferences items from outside PreferenceActivity.


回答1:


If you use a PreferenceAcitivity implicitly you are using a SharedPreference file. So, outside your PreferenceAcitivity you can access your SharedPrefence file and change it. Soon, those changes will be reflected on your PreferenceActivity.

You need a Context to access a SharedPreference. Look forward for example on onCreate method of other simpleAcitivity.

UPDATE: Using this approach you are not able to enable/disable items. You can change their values or remove them

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);

   // Restore preferences
   SharedPreferences settings = getPreferences(MODE);
   // Make sure we're running on Honeycomb or higher to use ActionBar APIs
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      //change your setting here
      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
   }

}

Other way, and on my opinion better and easier is Provide Alternative Resource. You can provide many xml files, that defines your app settings, according the Android API level, using a resource qualifier. For instance: v2, v17.

 res-v4
     setting.xml

 res-v17
     setting.xml -> This file can include specific Jelly Beans configs  


来源:https://stackoverflow.com/questions/15251667/how-to-change-state-of-a-preference-item-from-outside-the-preferenceactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!