0

After updating the target SDK version to 24.0.0, fromHtml becomes strikethroughed and a deprecation warning is returned. When it comes to setting the title of the action bar, what needs to change in order to resolve this error?

Minimum API is 17

actionBar.setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.welcome) + "</font>"));

'fromHtml(java.lang.String)' is deprecated

enter image description here

wbk727
  • 8,017
  • 12
  • 61
  • 125

2 Answers2

2

If your minSdkVersion is 24 or higher, use the version of fromHtml() that takes some flags as a parameter. AFAIK, FROM_HTML_MODE_LEGACY would be the flag value to use for compatibility with the older flag-less fromHtml().

If your minSdkVersion is lower than 24, your choices are:

  • Always use the fromHtml() you are, possibly using the quick-fix (Alt-Enter) to suppress the Lint warning

  • Use both versions of fromHtml(): the one taking the flags if your app is running on an API Level 24+ device, or the one without the flags on older devices

The latter would look like:

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
  actionBar.setTitle(Html.fromHtml(..., Html.FROM_HTML_MODE_LEGACY));
}
else {
  actionBar.setTitle(Html.fromHtml(...));
}

(where ... is your HTML to convert)

Note, though, that if you are simply trying to change the color of the entire action bar title, use Sandro Machado's solution. Html.fromHtml() and similar Spanned-based solutions are for cases where you need different colors for different pieces of text within a single TextView (or something using a TextView, such as the action bar).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
2

You should user other methods.

If you use a toolbar:

Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.someColor));
setSupportActionBar(toolbar);

A style:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
  </style>

  <style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
  </style>

  <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">@color/red</item>
  </style>
</resources>

Find more ways here: ActionBar text color

Community
  • 1
  • 1
Sandro Machado
  • 9,921
  • 4
  • 36
  • 57
  • You can and should use the `android.support.v7.widget.Toolbar`. Check it here: http://android-developers.blogspot.pt/2014/10/appcompat-v21-material-design-for-pre.html – Sandro Machado Aug 18 '16 at 23:42