簡體   English   中英

如何在回收器視圖的 onBindViewHolder() 方法中調用 getString()?

[英]How do I call getString() inside the onBindViewHolder() method of a recycler view?

語境

我正在創建一個 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()函數,因此我無法適當地格式化字符串以插入我需要的溫度,而無需使用雙精度值完全覆蓋字符串。

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

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

每個ViewHolder實例都有一個itemView場,這是一個實例View 每個View實例都有一個getContext()方法; 您可以使用它來訪問資源。

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

您可以使用上下文獲取字符串資源。

  context.getString(R.string.temperature)

您可以使用 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);
    }
//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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM