2016-01-13 25 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)); 

这可能会帮助你。

相关问题