Android getString方法

时间:2016-01-13 10:04:11

标签: android string

我正在尝试使用此代码将设置为string.xml的字符串值与日期连接起来:

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

但我发现错误:无法解决方法。 我试过这段代码:

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

有效,但值R.string.ore被检索为int值而不是字符串,但我需要一个字符串值 我需要使用string.xml的值,而不是使用简单的字符串示例“ore”

任何帮助?

3 个答案:

答案 0 :(得分:3)

如果您处于activity的上下文中,请使用此功能:

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

如果您处于fragment的上下文中,请使用此功能:

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 :(得分:2)

getStringContext的一种方法。如果无法解决,则表示您的类不是Context的子类。你可以用

holder.time.getContext()

检索您用于Context以及访问TextView的{​​{1}}。例如getString()

答案 2 :(得分:0)

试试这个,

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

这可能会对你有帮助。