setTextAppearance 在 API 级别 23 中已弃用

setTextAppearance deprecated in API level 23

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

我的问题:为什么它被弃用了?为什么它不再需要 Context?最重要的是,如何对旧版本使用 setTextAppearance(int resId)

  1. 旧版本如何使用setTextAppearance(int resId)

    这样使用:

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

    更多信息:

  2. 为什么它被弃用了?为什么它不再需要上下文?

    它被弃用的原因是不需要传递 context。它使用 View 提供的默认上下文。看看下面的源代码。这应该可以解释。

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

    这里的mContext定义在Viewclass。所以你不需要再将 Context 传递给这个方法。 TextView 将使用在创建期间提供给它的上下文。这样更有意义。

更新

此功能是作为支持库的一部分添加的。因此,请使用 TextViewCompat [documentation] 而不是 TextView。还有其他 classes 与此一起引入,例如 ImageViewCompat.

您可以使用 support/androidX 库中的 TextViewCompat

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

    // ...

    TextViewCompat.setTextAppearance(view, resId)

在内部,它从 API < 23 上的视图 (view.getContext()) 获取上下文。

Source for TextViewCompat

Source for TextView (API23)

以上答案是正确的 - 还有另一种方法。在 Kotlin 中,我写了一个扩展,如果你支持 SDK 23 及以下以及以上,它会让生活更轻松。

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