Android自定义TextView实现必填项前面的*号 您所在的位置:网站首页 小程序文本框必填改成选填 Android自定义TextView实现必填项前面的*号

Android自定义TextView实现必填项前面的*号

2024-06-16 17:55| 来源: 网络整理| 查看: 265

首先新建一个类继承TextView,然后重写setText,代码如下:

@Override public void setText(CharSequence text, BufferType type) { Spannable span = new SpannableString("*" + text); span.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); super.setText(span, type); }

xml布局部分代码如下:

效果如下所示:

但这种方法有一定的局限性,如果有一些TextView的必填项前缀不是*,颜色也不是红色,那就需要重新自定义TextView。略有点繁琐,所以可以将前缀跟颜色提取出来作为自定义属性来使用,下面使用另外一种方法来看一下。

首先在res目录下的values目录里新建一个xml文件,取名为attrs.xml,代码如下所示:

然后新建一个类继承TextView,代码如下所示:

import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.support.annotation.Nullable; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.widget.TextView; public class RequiredTextView extends TextView { private String prefix = "*"; private int prefixColor = Color.RED; public RequiredTextView(Context context) { super(context); } public RequiredTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RequiredTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, @Nullable AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RequiredTextView); prefix = ta.getString(R.styleable.RequiredTextView_prefix); prefixColor = ta.getInteger(R.styleable.RequiredTextView_prefix_color, Color.RED); String text = ta.getString(R.styleable.RequiredTextView_android_text); if (TextUtils.isEmpty(prefix)) { prefix = "*"; } if (TextUtils.isEmpty(text)) { text = ""; } ta.recycle(); setText(text); } public void setText(String text) { Spannable span = new SpannableString(prefix + text); span.setSpan(new ForegroundColorSpan(prefixColor), 0, prefix.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); setText(span); } }

以上代码理解起来不难,主要是在初始化TextView的时候取出前缀属性跟前缀颜色属性,然后使用Spannable设置前缀。activity对应的布局代码如下:

上面是默认的前缀跟颜色,下面是自定义的前缀跟颜色,效果如下图所示:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有