项目中需要实现正常情况下一种默认色彩,获取焦点后下划线变色,如果失去焦点,检验输入值改变颜色。我们知道下划线是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));
}
}
}
}