2016-01-13 59 views
0

我試圖來連接子系統內置於string.xml使用此代碼日期的字符串值:的Android getString方法

holder.time.setText(date.getHours()+" " + getString(R.string.ore)); 

但我recive錯誤:無法解析方法。 我嘗試此代碼:

holder.time.setText(date.getHours()+" " +R.string.ore); 

作品,但價值R.string.ore檢索爲int值,而不是字符串,但我需要一個字符串值 我需要string.xml使用的值,而不是用一個簡單的字符串例如「礦石」

任何幫助?

+1

請試試看:'getResources()。getString(R.string.ore)' –

+0

這應該在任何地方工作:'holder.time.getContext()。getString(R.string.ore)'。 –

回答

3

如果您在activity是的情況下,使用這樣的:如果你在一個fragment

getResources().getString(R.string.ore); 

「:如果你

getActivity().getResources().getString(R.string.ore); 

的上下文,使用此在adapter之內,您需要通過適配器的構造函數將容器活動的上下文傳遞給它。

// When creating the adapter, pass the activity's context 
// keeping in mind the notes above 
YourAdapter adapter = new YourAdapter(this, ...); 

從適配器中:

private Context mContext; // A member variable of the adapter class 

public YourAdapter(Context context, ...) { 
    mContext = context; 
} 

然後你就可以得到你的字符串資源是這樣的:

mContext.getResources().getString(R.string.ore); 
+1

看起來他是在一個「適配器」中。 –

+0

@JaredBurrows你是對的,我會更新我的答案。 –

+0

如果您使用的是適配器,您應該已經可以訪問'context'。 –

2

getStringContext的方法。如果解決不了,這意味着你的班級不是Context的子類。你可以使用

holder.time.getContext() 

檢索Context您使用的是膨脹和TextView訪問getString()。例如holder.time.getContext().getString(R.string.hour)

0

試試這個,

Calendar calendar = Calendar.getInstance(); 
holder.time.setText(calendar.get(Calendar.HOUR)+" " +getString(R.string.ore)); 

這可能會幫助你。

相關問題