自定义EditText设置底部下划线在各种状态下颜色改变

自定义EditText设置底部下划线在各种状态下颜色改变

144 
作者  nicegoing 
2016.06.20 08:48  字数 377  阅读 2245 评论 0

项目中需要实现正常情况下一种默认色彩,获取焦点后下划线变色,如果失去焦点,检验输入值改变颜色。我们知道下划线是EditText的background,那么可以给它一个background并设置在不同的状态下改变background的值。

background使用shape绘制
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item  android:id="@+id/shape"
        android:bottom="1dp"
        android:left="-10dp"
        android:right="-10dp"
        android:top="-10dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke android:width="1dp" android:color="@color/color_f1f1f1"/>
        </shape>
    </item>
</layer-list>
EditText
public class AddressEditText extends EditText implements View.OnFocusChangeListener {
    private Context context;


    public void setOnCheckInputListener(OnCheckInputListener onCheckInputListener) {
        this.onCheckInputListener = onCheckInputListener;
    }

    private OnCheckInputListener onCheckInputListener;
    private GradientDrawable     drawable;

    /**
     * 检测输入是否符合要求的回调
     */
    public interface OnCheckInputListener {
        /**
         * 检测输入的方法
         *
         * @param v   点击的view
         * @param str 输入的字符串
         * @return 检测成功返回true, 检测失败返回false
         */
        boolean checkInput(View v, String str);
    }

    public AddressEditText(Context context) {
        this(context, null);
    }

    public AddressEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        LayerDrawable layerDrawable = (LayerDrawable) getBackground();
        drawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.shape);
        setOnFocusChangeListener(this);
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            LogUtil.i("获取焦点");
            drawable.setStroke(ResourceUtil.getDimens(R.dimen.dp_1), ResourceUtil.getColor(R.color.color_d1d1d1));
        } else {
            LogUtil.i("失去焦点");

            if (onCheckInputListener != null && onCheckInputListener.checkInput(this, getText().toString().trim())) {
                drawable.setStroke(ResourceUtil.getDimens(R.dimen.dp_1), ResourceUtil.getColor(R.color.color_f1f1f1));

            } else if (onCheckInputListener == null) {
                drawable.setStroke(ResourceUtil.getDimens(R.dimen.dp_1), ResourceUtil.getColor(R.color.color_f1f1f1));
            } else {
                drawable.setStroke(ResourceUtil.getDimens(R.dimen.dp_1), ResourceUtil.getColor(R.color.color_ff6f00));

            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值