安卓中的getString()返回了错误的字符串

6

我遇到了一个问题,即getString()方法返回的不是id对应的字符串,而是另一个字符串。这是我的代码:

public public class ShopFragment extends Fragment {
    ...
    public class ShopManager(){
        ...
        private TableRow[] getRowsFromItems(){
        ...
        TextView headlineName = new TextView(getContext());
        headlineName.setText(getString(R.string.shop_headline_name));
        TextView headlinePrice = new TextView(getContext());
        headlinePrice.setText(getString(R.string.shop_headline_price));
        ...
        }
    }
}

strings.xml:

<resources>
    ...
    <string name="show_leaderboards">Leaderboards</string>
    <string name="show_achievements">Achievements</string>
    ...
    <string name="shop_headline_name">Article</string>
    <string name="shop_headline_price">Price</string>
    ...
</resources>

问题是,getString(R.string.shop_headline_name)返回的是“成就”,getString(R.string.shop_headline_price)返回的是“排行榜”。我不知道如何解决这个问题,也很困惑为什么会发生这种情况。我做错了什么吗? 感谢您的答复。

4
尝试清理项目(例如,在Android Studio中选择“构建”>“清理项目”),看看是否有帮助。 - CommonsWare
1
如果你启用了即时运行,它可能会导致这个问题。它仍然是一个有问题的东西,不要使用它! - Sufian
2个回答

11

使用清理和构建操作应该可以解决问题。您的R.java文件保存了所有的id,但是可能没有正确生成。清理和构建操作可以正确地生成它。


1
使用来自资源文件夹(这里是strings.xml)的字符串,请使用以下代码:
```` R.string.your_string_name ````
headlineName.setText(getResources().getString(R.string.shop_headline_name));

这应该可以工作。

getString(int resId) 内部实现了 getResources().getString(resId)。因此,不需要使用 getResource()。 - Tony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接