处理没有魔术字符串的Android首选项

我使用 Androids built in way处理首选项,通过写入xml文件中的所有设置.这真的很好,但是在xml和Java代码中没有使用魔术字符串的情况下,我找不到任何好的方法.

唯一可以想到的办法是将首选项保存为String,但是也不会感到正确.任何人有一个很好的解决方法

解决方法

您可以将“魔术字符串”移动到字符串资源:

在你偏好xml文件中:

<EditTextPreference
        android:key="@string/preferences_pdn_key"
        android:title="@string/preferences_pdn_title"
        android:summary="@string/preferences_pdn_summary"
        android:dialogMessage="@string/input_pdn_message" />

在values / strings.xml文件中:

...
<string name="preferences_pdn_key">pdn</string>
...

然后,您可以从您的活动或偏好活动中引用偏好:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdnKey = getString(R.string.prefernece_pdn_key);
String pdn = sharedPreferences.getString(pdnKey,null);

如果你不喜欢从字符串资源中获取首选项,那么你可以再做一个技巧:

public class PreferenceNames {

    /* categories */ 
    public static final String LoginCategory = MyApplication.getResourceString(R.string.preferences_login_category_key);
    ...

    /* preferences */   
    public static final String Pdn = MyApplication.getResourceString(R.string.preferences_pdn_key);
    ...
}

所以你现在可以用下面的方式引用你的偏好键:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdn = sharedPreferences.getString(PreferenceNames.Pdn,null);

这里是您的MyApplication类应如下所示:

public class MyApplication extends Application {    
    private static VvmApplication s_instance;

    public MyApplication(){
        s_instance = this;
    }

    public static Context getContext(){
        return s_instance;
    }

    public static String getResourceString(int resId){
        return getContext().getString(resId);       
    }
}

另外你需要添加下一件事你的AndroidManifest.xml:

<application android:name="com.mypackage.application.MyApplication" ... >
...
</application>

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...