自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="NecessaryTextView">
<attr name="necessary" format="boolean" />
</declare-styleable>
</resources>
自定义控件
import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class NecessaryTextView : AppCompatTextView {
private var necessary = false
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.NecessaryTextView)
necessary = typedArray.getBoolean(R.styleable.NecessaryTextView_necessary, false)
typedArray.recycle()
setText(text, null)
}
override fun setText(text: CharSequence?, type: BufferType?) {
if (necessary) {
val span = SpannableString("*$text")
span.setSpan(ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
super.setText(span, type)
} else {
super.setText(text, type)
}
}
}