2013-05-11 59 views
2

我想打一个观点有两种不同的颜色,所以我想在我的fragment安卓:根据需要

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

这个代码文本字符串资源不工作,它说“欢迎来到空”

然后我尝试这个

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

,我也得到 “欢迎x1029203”

这是在实际的R.java文件中找到的string值的int的参考。任何帮助表示感谢。

回答

3

如果你只是的setText(R.string.sample),那么它是OK的,但如果你添加了一些它需要

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

再次感谢您!答案接受...在9分钟=) – IrishWhiskey 2013-05-11 23:57:02

0

welcome_text_ID不能资本

此外,串不能成为一个观点的ID。

这是正确的代码:

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

为什么不能把id大写? – 2013-05-11 23:57:02

+0

它工作正常与“ID”大写,但你是正确的,它使你设置样品为'视图'不'字符串' – IrishWhiskey 2013-05-11 23:58:05

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); 
    } 
+1

谢谢!他们都工作,Hoan是第一名,所以我会检查他。 – IrishWhiskey 2013-05-11 23:56:33