Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Context

I am creating a RecyclerAdapter to display the forecast info on a certain day. My RecyclerView contains multiple days, each of which is modified with the onBindViewHolder.

The layout of each day has 3 text views. The first one contains a string that is the summary. The second one contains a string with a double as a positional argument which represents the low temperature. The third is identical to the second, but represents the high temperature.

Below is the code of my onBindViewHolder method:

@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());
}

Issue

Since high and low temperatures are doubles, I need to format the string accordingly, lest I overwrite the string with just a double value. Here are the string resources for high temperature and low temperature:

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

Outside of the RecyclerAdapter class I know how to do this, below is an example of how I format a string inside a Fragment:

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

However, I don't have access to the getString() function inside the RecyclerAdapter, so I cannot format the string appropriately to insert the temperature I need without completely overriding the String with a double.

Question

How do I use getString() inside the onBindViewHolder() method?

like image 570
isakbob Avatar asked Oct 11 '18 16:10

isakbob


2 Answers

How do I use getString() inside the onBindViewHolder() method?

Every ViewHolder instance has an itemView field, which is an instance of View. Every View instance has a getContext() method; you can use this to access resources.

String text = viewHolder.itemView.getContext().getString(R.string.mystring);
like image 141
Ben P. Avatar answered Sep 21 '22 10:09

Ben P.


You can you get string resource using context.

  context.getString(R.string.temperature)
like image 41
Ramesh Yankati Avatar answered Sep 17 '22 10:09

Ramesh Yankati