处理没有魔术字符串的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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...