如何在回收者视图的onBindViewHolder()方法内调用getString()?

时间:2018-10-11 16:43:02

标签: android android-studio recycler-adapter

上下文

我正在创建一个RecyclerAdapter来显示某一天的天气预报信息。我的RecyclerView包含多天,每一天都可以通过onBindViewHolder进行修改。

每天的布局有3个文本视图。第一个包含作为摘要的字符串。第二个包含一个字符串,该字符串的位置参数为double,代表低温。第三个与第二个相同,但是代表高温。

下面是我的onBindViewHolder方法的代码:

@Override
public void onBindViewHolder(@NonNull DailyForecastAdapter.ViewHolder viewHolder, int i) {

    Datum datum = forecast.get(i);

    TextView summary = viewHolder.summaryTextView;
    TextView tempHigh = viewHolder.tempHighTextView;
    TextView tempLow = viewHolder.tempLowTextView;

    summary.setText(datum.getSummary());
    tempHigh.setText(datum.getTemperatureHigh());
    tempLow.setText(datum.getTemperatureLow());
}

问题

由于高温和低温是 doubles ,因此我需要相应地设置字符串格式,以免仅用double值覆盖字符串。这是高温和低温的字符串资源:

<string name="temperature_high">High of %1$.2f</string>
<string name="temperature_low">Low of %1$.2f</string>

在RecyclerAdapter类之外,我知道该怎么做,以下是如何在Fragment内格式化字符串的示例:

 String moddedString = String.format(getString(R.string.temperature), temp);
 ((TextView)activity.findViewById(R.id.temperatureDisplay)).setText(moddedString);

但是,我无权访问RecyclerAdapter内部的getString()函数,因此我无法正确格式化字符串以插入所需的温度,而不会用

问题

如何在getString()方法中使用onBindViewHolder()

4 个答案:

答案 0 :(得分:5)

  

如何在onBindViewHolder()方法中使用getString()?

每个ViewHolder实例都有一个itemView字段,它是View的实例。每个View实例都有一个getContext()方法;您可以使用它来访问资源。

String text = viewHolder.itemView.getContext().getString(R.string.mystring);

答案 1 :(得分:1)

您可以使用上下文获取字符串资源。

  context.getString(R.string.temperature)

答案 2 :(得分:0)

您可以使用RecyclerViewAdapter类的构造函数保存Context的本地副本:

public class YourRecyclerViewAdapter extends RecyclerView.Adapter<YourRecyclerViewAdapter.ViewHolder> {


    private Context context;


    public YourRecyclerViewAdapter(Context context) {
        this.context = context;
    }


    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        String string = context.getString(R.string.your_string);
    }

答案 3 :(得分:0)

//1. Get context from adapter constructor:
public YourRecyclerViewAdapter(Context context) 


//2. As @Ben P.said, get context from item view:
Context context = viewHolder.itemView.getContext();


//3. I think the adapter only binds the data to the view 
//and doesn’t care about the logic, so maybe you can 
//prepare the data before passing it to the adapter
CustomData {
    private String temperature;
    public String getTemperature() {
          return temperature;
    }
}
    
//Then pass the data to adapter by construtor:
YourRecyclerViewAdapter adapter = new YourRecyclerViewAdapter(data);

//Or update data by adapter functions:
adapter.updateData(data);