2013-05-11 63 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