美文网首页
Android自定义TextView实现必填项前面的*号

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

作者: 爺珍爱那颗心 | 来源:发表于2020-04-21 22:14 被阅读0次
  • 在res目录下的values目录里新建一个xml文件,取名为attrs.xml,代码如下所示:
<?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,代码如下所示:
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来自定义颜色和头部符号
  app:prefix="++"
  app:prefix_color="#FF6100"

相关文章

网友评论

      本文标题:Android自定义TextView实现必填项前面的*号

      本文链接:https://www.haomeiwen.com/subject/jhwmihtx.html