如何在runTime中更改R.String ....值

时间:2015-08-27 13:10:29

标签: android

我有一个静态值

MyCntrl as vm

我正在尝试在运行时更改此值。但无法做到

3 个答案:

答案 0 :(得分:3)

你不能尝试这样做,这不是好方法。 您总是可以检索它们,使用它们并在必要时修改它们,并在需要保存状态时保存它们。您可以使用SharedPreferences轻松地在执行之间保存数据。

答案 1 :(得分:2)

您无法动态更改strings.xml,因为它是已编译的资源。但您可以使用sharedPreference动态更改值。

答案 2 :(得分:0)

您无法在runTime中修改strings.xml。如果您想在手机的存储空间中存储一些字符串,请使用SharedPreferences。这就是我通常使用它的方式:

public class Preferences {

    // Constant key values
    public static final String SERVER_IP  = "Server"; 
    // {....}
    public static final String SOUND = "Notif sound";


    // Required classes for SharedPreferences
    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;

    public Preferences(Context context) {
        this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
        this.editor = this.sharedPreferences.edit();
    }

    /**
     * Set a new value in the shared preferences.
     * <p>
     * You can get the value by the get function.
     * @param key   key of the value, one of the constant strings of {@link Preferences}'s.
     * @param value the value, that should be stored.
     *
     * @see     #get(String, String)
     *
     */
    public void set(String key, String value) {
        this.editor.putString(key, value);
        this.editor.commit();
    }

    /**
     * Get the value of a previously set data if exact or return the default value if not.
     * @param key           key of the value, one of the constant strings of {@link Preferences}'s.
     * @param defaultValue  the default value, return this if the key is not in the database.
     * @return              the value belongs to the key or the default value.
     *
     * @see     #set(String, String)
     */
    public String get(String key, String defaultValue) {
        return this.sharedPreferences.getString(key, defaultValue);
    }

    /**
     * Removes a key value pair from the database.
     * @param key   The key of the pair which should be removed.
     */
    public void clear(String key) {
        this.editor.remove(key);
        this.editor.commit();
    }

    /**
     * Delete all key value pairs from the database.
     */
    public void clear() {
        Log.d(TAG,"SharedPreferences cleared");
        this.editor.clear();
        this.editor.commit();
    }
}