Android

Daniel Weschke

March 15, 2019

1 TextView

1.1 Multi-line

<resources>
    <string name="weather_outdoor">Weather data for %s %s
        \n{icon} %s (%s %%)
        \nTemperature: %s °C  %s / %s feels: %s
        \nHumidity: %s %%
        \nPressure: %s hPa
        \nWind: %s km/h %s
        \nSunrise / sunset: %s / %s</string>
TextView tv = findViewById(v);
tv.setText(String.format(getString(R.string.weather_outdoor),
        name, dt,
        description, clouds,
        temp, tempMin, tempMax, apparent,
        humidity,
        pressure,
        speed, deg,
        sunrise, sunset));

1.2 Multi-line with html tags

<resources>
    <string name="weather_outdoor"><![CDATA[<b>Weather data for %s %s
        <br/>{icon} %s (%s %%)
        <br/>Temperature: %s °C — %s / %s feels: %s
        <br/>Humidity: %s %%
        <br/>Pressure: %s hPa
        <br/>Wind: %s km/h %s
        <br/>Sunrise / sunset: %s / %s]]></string>
TextView tv = findViewById(R.id.textViewWeatherOutdoor);
tv.setText(Html.fromHtml(getString(R.string.weather_outdoor)));
TextView tv = findViewById(v);
tv.setText(Html.fromHtml(String.format(getString(R.string.weather_outdoor),
        name, dt,
        description, clouds,
        temp, tempMin, tempMax, apparent,
        humidity,
        pressure,
        speed, deg,
        sunrise, sunset)));

1.3 Replace sub-string with an image

TextView tv = findViewById(v);
SpannableStringBuilder ssb = new SpannableStringBuilder(tv.getText());
Context context = getApplicationContext();
int id = context.getResources().getIdentifier("openweathermap_" + icon, "drawable", context.getPackageName());
String weather = tv.getText().toString();
ssb.setSpan(new CenteredImageSpan(context, id), weather.indexOf("{icon}"), weather.indexOf("{icon}")+6, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv.setText(ssb, TextView.BufferType.SPANNABLE);