如何从preferenceActivity外更改preference项目的状态?状态、项目、preferenceActivity、preference

由网友(独念旧时长安街)分享简介:有我的应用程序的某些功能需要的Andr​​oid 4.2以上版本。所以在我的主要活动,我需要检查可用的操作系统的功能和修改(启用/禁用),这是在我的 preferenceActivity 定义preferences项目。 There are some features in my app which require...

有我的应用程序的某些功能需要的Andr​​oid 4.2以上版本。所以在我的主要活动,我需要检查可用的操作系统的功能和修改(启用/禁用),这是在我的 preferenceActivity 定义preferences项目。

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.

以下code是从外部无法访问的 preferenceActivity

The following code is unreachable from outside the PreferenceActivity

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

所以我的问题是如何修改从外面preferenceActivity preferences项目。

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

推荐答案

如果您使用的是preferenceAcitivity隐含您使用的是共享preference文件。所以,你的preferenceAcitivity以外,您可以访问你的共享prefence文件,并改变它。不久,这些变化将在你的preferenceActivity得到体现。

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.

您需要上下文来访问共享preference。期待例如在其他simpleAcitivity的onCreate方法。

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

的更新:的使用这种方法,你是不是能够启用/禁用物品。你可以改变它们的值或删除

@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();
   }

}

其他的方式,并在我看来更好,更容易为提供替代资源即可。您可以提供许多的XML文件,定义您的应用程序的设置,根据Android的API级别,使用资源预选赛。例如:V2,V17

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  
阅读全文

相关推荐

最新文章