setTextAppearance deprecated in API level 23

AndroidDeprecated

Android Problem Overview


> public void setTextAppearance (Context context, int resId) Added in API level 1
This method was deprecated in API level 23. Use setTextAppearance(int) instead.

My Question: Why it's been deprecated? Why it doesn't need Context anymore? And most importantly, how to use setTextAppearance(int resId) for older versions?

Android Solutions


Solution 1 - Android

You can use TextViewCompat from the support/androidX library:

    import android.support.v4.widget.TextViewCompat // for support-library
    import androidx.core.widget.TextViewCompat      // for androidX library
    
    // ...

    TextViewCompat.setTextAppearance(view, resId)

Internally it gets the context from the view (view.getContext()) on API < 23.

Source for TextViewCompat

Source for TextView (API23)

Solution 2 - Android

  1. how to use setTextAppearance(int resId) for older versions?

Use it like this:

    if (Build.VERSION.SDK_INT < 23) {
        super.setTextAppearance(context, resId);
    } else {
        super.setTextAppearance(resId);
    }

For more info: https://stackoverflow.com/a/33393762/4747587

  1. Why it's been deprecated? Why it doesn't need Context anymore?

The Reason why it is deprecated is there is no need to pass a context. It uses the default context provided by the View. Look at the source code below. That should explain it.

    public void setTextAppearance(@StyleRes int resId) {
         setTextAppearance(mContext, resId);
    }

The mContext here is defined in the View class. So you need not pass a Context to this method anymore. The TextView will use the context provided to it during it's creation. That makes more sense.

UPDATE

This functionality is added as part of the Support Library. So instead of TextView, use TextViewCompat [documentation]. There are also other classes introduced along with this, like ImageViewCompat.

Solution 3 - Android

The above answer is correct - here's another way too. In Kotlin I wrote an extension which makes life easier if you do support SDK 23 and below as well as above.

   fun TextView.setAppearance(context: Context, res: Int) {
        if (Build.VERSION.SDK_INT < 23) {
            setTextAppearance(context, res)
        } else {
            setTextAppearance(res)
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlireza FarahaniView Question on Stackoverflow
Solution 1 - AndroidRustamGView Answer on Stackoverflow
Solution 2 - AndroidHenryView Answer on Stackoverflow
Solution 3 - AndroidazwethinkweizView Answer on Stackoverflow