Android:字符串资源无法正常工作

时间:2013-05-11 23:50:47

标签: android android-fragments

我想让视图中包含两种不同颜色的文字,所以我在fragment

中尝试此代码
TextView welcome = (TextView) view.findViewById(R.id.welcome_text_ID);
View sample = getActivity().findViewById(R.string.sample);
welcome.setText("Welcome to " + sample);

它说“欢迎来到null”

然后我尝试了这个

TextView welcome = (TextView) view.findViewById(R.id.welcome_text_ID);
welcome.setText("Welcome to " + (R.string.sample));

我得到“欢迎来到x1029203”

在实际int文件中找到的stringR.java的引用。感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

如果你只是setText(R.string.sample)那就没关系了,但是如果你添加一些东西就需要

welcome.setText("Welcome to " + getString(R.string.sample));

答案 1 :(得分:3)

你必须这样做:

welcome.setText("Welcome to " + getResources().getString((R.string.sample)));

有点偏离,为什么getResources().getString(Id)getString()都有效:

如果您查看source code of Fragment.java,您会看到getString()来电getResources().getString(Id),所以两者都是相同的:

 public final String getString(int resId) {
        return getResources().getString(resId);
    }

答案 2 :(得分:0)

welcome_text_ID无法大写

此外,字符串不能是视图的ID。

这是正确的代码:

View sample = getActivity().findViewById(R.id.sample);