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());
}
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.
How do I use getString()
inside the onBindViewHolder()
method?
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);
You can you get string resource using context.
context.getString(R.string.temperature)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With