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必填项星号*内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Android OpenGL入门之GLSurfaceView
这篇文章主要介绍了OpenGL入门知识,如何在Android中使用GLSurfaceView,如果对OpenGL感兴趣的同学,可以参考下2021-04-04
Android使用AudioManager修改系统音量的方法
这篇文章主要介绍了Android使用AudioManager修改系统音量的方法,结合实例形式分析了AudioManager调节音量的常用方法及相关使用技巧,需要的朋友可以参考下2016-08-08
android中soap协议使用(ksoap调用webservice)
kSOAP是如何调用ebservice的呢,首先要使用SoapObject,这是一个高度抽象化的类,完成SOAP调用。可以调用它的addProperty方法填写要调用的webservice方法的参数2014-02-02


最新评论