Android TextView前增加红色必填项星号*的示例代码
作者:命运之手
TextView是一个完整的文本编辑器,但是基类为不允许编辑,其子类EditText允许文本编辑,这篇文章主要介绍了Android TextView前增加红色必填项星号*的示例代码,需要的朋友可以参考下
TextView是什么
向用户显示文本,并可选择允许他们编辑文本。TextView是一个完整的文本编辑器,但是基类为不允许编辑;其子类EditText允许文本编辑。
咱们先上一个图看看TextView的继承关系:

从上图可以看出TxtView继承了View,它还是Button、EditText等多个组件类的父类。咱们看看这些子类是干嘛的。
- Button:用户可以点击或单击以执行操作的用户界面元素。
- CheckedTextView:TextView支持Checkable界面和显示的扩展。
- Chronometer:实现简单计时器的类。
- DigitalClock:API17已弃用可用TextClock替代。
- EditText:用于输入和修改文本的用户界面元素。
- TextClock:可以将当前日期和/或时间显示为格式化字符串。
下面来看看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 = 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)
}
}
}到此这篇关于Android TextView前增加红色必填项星号*的示例代码的文章就介绍到这了,更多相关Android TextView必填项星号*内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
