前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android自定义TextView实现必填项前面的*号

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

作者头像
longzeqiu
发布2020-04-24 15:26:18
1.5K0
发布2020-04-24 15:26:18
举报
文章被收录于专栏:Android小知识Android小知识
  • 在res目录下的values目录里新建一个xml文件,取名为attrs.xml,代码如下所示:
代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RequiredTextView">
        <attr name="android:text" />
        <attr name="prefix" format="string|reference" />
        <attr name="prefix_color" format="color|reference" />
    </declare-styleable>
</resources>
  • 新建一个类继承TextView,代码如下所示:
代码语言:javascript
复制
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);
    }
 
}
  • 默认效果为前面是红色*
  • 可以通过我们写的attrs来自定义颜色和头部符号
代码语言:javascript
复制
  app:prefix="++"
  app:prefix_color="#FF6100"
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档