如何使用editor.putString(sharedpreference)修改我的String.xml文件中的字符串值? [英] how to modify a string value in my String.xml file using editor.putString (sharedpreference)?

查看:226
本文介绍了如何使用editor.putString(sharedpreference)修改我的String.xml文件中的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Editor ed=prefs.edit();
ed.putString(getString(R.string.firsttemplate), "String Modified");
ed.apply();
ed.commit();
Toast.makeText(getBaseContext(), getString(R.string.firsttemplate), Toast.LENGTH_SHORT).show();

此Toast显示了保存在我的字符串值中的先前文本

this Toast is showing the previous text saved in my string value

我也已经看到有关SharedPreferences的问题,但这并没有帮助。

I also saw already asked questions about SharedPreferences but it wasn't helpful.

推荐答案

您无法在运行时更改资源文件。字符串是硬编码在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());

这篇关于如何使用editor.putString(sharedpreference)修改我的String.xml文件中的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆