修复android TextView FontWeight不生效以及代码设置

修复android TextView FontWeight不生效以及代码设置

修复android TextView bug FontWeight不生效以及代码设置

不生效原因具体原因看这里:https://blog.csdn.net/qq_21793463/article/details/142444607

总结:androidx bug 导致的即便xml 写TextView 也会被替换AppCompatTextView。这里主要就是AppCompatTextView 有问题

1.要么自定义view继承写TextView ,最简单但是不支持动态设置权重,但是也会提示让继承AppCompatTextView,处理不好还是有问题

2.直接继承AppCompatTextView

点击查看代码

import android.content.Context

import android.os.Build

import android.util.AttributeSet

import androidx.annotation.IntRange

import androidx.appcompat.R

import androidx.core.graphics.TypefaceCompat

class FontWeightTextView(context: Context, attrs: AttributeSet?) :

androidx.appcompat.widget.AppCompatTextView(context, attrs) {

var textFontWeight: Int = 400 // 默认值

set(@IntRange(from = 1, to = 1000) value) {

field = when {

value < 1 -> 1

value > 1000 -> 1000

else -> value

}

TypefaceCompat.create(context, typeface, field, typeface.isItalic).let {

typeface = it

}

}

get() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {

return typeface.weight

}

return field

}

init {

attrs?.let {

val a = context.obtainStyledAttributes(attrs, R.styleable.TextAppearance)

textFontWeight = a.getInt(R.styleable.TextAppearance_android_textFontWeight, textFontWeight)

a.recycle()

}

}

override fun setTextAppearance(context: Context, resId: Int) {

super.setTextAppearance(context, resId)

val a = context.obtainStyledAttributes(resId, R.styleable.TextAppearance)

textFontWeight = a.getInt(R.styleable.TextAppearance_android_textFontWeight, textFontWeight)

a.recycle()

}

}

相关推荐

被恶意差评如何起诉
北海365最新房屋出租

被恶意差评如何起诉

📅 06-30 ❤️ 409
与电影相关的100个英文词汇
北海365最新房屋出租

与电影相关的100个英文词汇

📅 07-07 ❤️ 946
持牌、备案,还是一刀切?现金贷或将迎史上最严监管
北海365最新房屋出租

持牌、备案,还是一刀切?现金贷或将迎史上最严监管

📅 07-30 ❤️ 649