本文主要是介绍【Android】TextView前增加红色必填项星号*,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自定义属性
<?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// TextView that start with a red char of *
class NecessaryTextView : AppCompatTextView {private var necessary = falseconstructor(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)}}
}
这篇关于【Android】TextView前增加红色必填项星号*的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!