欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

AndroidTextView前增加红色必填项星号*的示例代码,

来源: 开发者 投稿于  被查看 17906 次 评论:86

AndroidTextView前增加红色必填项星号*的示例代码,


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必填项星号*内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • Android TextView渐变颜色和方向及动画效果的设置详解
  • Android使用AutoCompleteTextView实现自动填充功能的案例
  • 基于Android中的 AutoCompleteTextView实现自动填充

用户评论