如何从另一个 activity 获取 TextPreference 的值?

How to get a TextPreference's value from another activity?

我的设置 activity 中有一个 TextPreference,我想从另一个 activity 中获取变化的值。 startActivityForResult() 方法有帮助吗?

偏好xml:

<EditTextPreference
    android:key="@string/pref_location_key"
    android:title="@string/pref_location_label"
    android:defaultValue="@string/pref_location_default"
    android:inputType="text"
    android:singleLine="true" />

我通常如下使用首选项实用程序 class,然后根据需要将静态导入 Activity 或片段。这是您应用于 Google 的 iosched 2014 应用程序中使用的首选项 class 的示例。

/*

* 版权所有 2014 Google Inc. 保留所有权利。 * * 根据 Apache 许可证 2.0 版("License")获得许可; * 除非遵守许可证,否则您不得使用此文件。 * 您可以在以下位置获得许可证副本 * * http://www.apache.org/licenses/LICENSE-2.0 * * 除非适用法律要求或书面同意,软件 * 根据许可证分发是在 "AS IS" 基础上分发的, * 没有任何明示或暗示的保证或条件。 * 请参阅许可证以获取特定语言的管理权限和 * 许可限制。 */

包 com.your.package;

/** * 与应用偏好相关的实用程序和常量。 */ public class PrefUtils {

public static final String pref_location_key = "pref_location_key";

public static String getPrefLocationKey(final Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    return sp.getString(pref_location_key, "map");
}

public static void setPrefLocationKey(final Context context, String _pref_location_key) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    sp.edit().putString(pref_location_key, _pref_location_key).apply();
}

}

以上将 link 并根据您在 preference.xml 文件中的值进行操作,只要 String pref_location_key = "pref_location_key"; 值与您的首选项文件中的值匹配。

请注意,您可以将 .apply() 更改为 .commit(),这取决于您希望以多快或多积极的方式访问该值,但请注意,您可能还必须解决立即访问该值的问题如果需要立即将其传递给下一个意图,或者您也可以使用第三方库 EventBus EventBus link 将其传递给其他活动或片段,如果您想触发 action/event 以及该值设置和松耦合。

因此在您的 Activity 中您可以调用 getPrefLocationKey(getBaseContext())setPrefLocationKey(getBaseContext(), "Your desired value to set the string to.")

在片段中,上下文将以 activity 开头,因为片段没有上下文。 getPrefLocationKey(getActivity().getBaseContext()) ` or `setPrefLocationKey(getActivity().getBaseContext(), "Your desired value to set the string to.")

在大多数情况下,在 Activity 中 getBaseContext() 可以替换为 this

在所有情况下,setPrefLocationKey 或 getPrefLocationKey 都应该静态导入到您的 Activity 或片段中。

PreferencesActivityPreferencesFragment 是实用程序 类,可直接将用户首选项存储和更新到 SharedPreferences。 要阅读它们,您只需调用 getDefaultSharedPreferences(context) 然后调用 sharedPreferences.getString(your_preferences_key);.

Android Settings guide #Reading prefs 中提供了更多信息。