2

I want to make a view have text with two different colors so I'm trying this code inside my fragment

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

and it says "Welcome to null"

Then I tried this

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

and i get "Welcome to x1029203"

Which is the reference of the int of that string value found in the actual R.java file. Any help is appreciated thanks.

4

3 回答 3

3

你必须这样做:

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

一个小插曲,为什么两者都getResources().getString(Id)有效getString()

如果您查看 的源代码Fragment.java,您会看到,getString()调用getResources().getString(Id),所以两者是相同的:

 public final String getString(int resId) {
        return getResources().getString(resId);
    }
于 2013-05-11T23:53:43.010 回答
3

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

welcome.setText("Welcome to " + getString(R.string.sample));
于 2013-05-11T23:52:31.490 回答
0

welcome_text_ID不能大写

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

这是正确的代码:

View sample = getActivity().findViewById(R.id.sample);
于 2013-05-11T23:52:45.380 回答