項目中需要實現正常情況下一種默認色彩,獲取焦點后下劃線變色,如果失去焦點,檢驗輸入值改變顏色。我們知道下劃線是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));
}
}
}
}