且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用editor.putString(sharedpreference)修改我的String.xml文件中的字符串值?

更新时间:2022-01-11 05:58:14

您无法在运行时更改资源文件。字符串是硬编码在string.xml文件中的,因此在运行时无法更改。如果您要尝试的话,只需使用SharedPreferences来存储用户的首选项即可。

You can't change resource files during runtime. Strings are hard-coded in the string.xml file and hence can't be changed during runtime. Instead of trying to edit your strings.xml file, just use SharedPreferences to store the user's preferences if that's what you're trying.

您可以使用此代码作为基础您可以从SharedPreferences中保存和恢复值。

You can use this code is basis for you saving and restoring values from SharedPreferences.

public class Account {

private static Account account;
private static final String ACCESS_TOKEN = "access_token";
public String accessToken;

public static Account getInstance() {
    if (account == null)
        account = new Account();
    return account;
}

public void save(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    Editor editor = prefs.edit();

    editor.putString(ACCESS_TOKEN, accessToken);

    editor.commit();
}

public void restore(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    accessToken = prefs.getString(ACCESS_TOKEN, accessToken);
}

private Account() {

}
}

现在,您可以像这样访问您的值。恢复:

Now you can access your values like this. Restoring:

Account account = Account.getInstance();
account.restore(getActivity());
Toast.makeText(getActivity(), account.accessToken, Toast.LENGTH_SHORT).show();

保存:

Account account = Account.getInstance();
account.accessToken = "newString";
account.save(getActivity());