经过大量研究和排列后问题得到解决-(也感谢@van)
创建一个将扩展的新类EditText
像这样的东西-
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
}
使用此类作为 xml 中的视图,如下所示-
<com.raj.poc.MyEditText
android:id="@+id/et_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
现在在第三步,只需设置一个TextWatcher
像这样的自定义文本视图-
et = (MyEditText) findViewById(R.id.et_test);
errorIcon = getResources().getDrawable(R.drawable.ic_error);
errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight()));
et.setError(null,errorIcon);
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if(s.toString().length()>6){
et.setError("", null);
}else{
et.setError("", errorIcon);
}
}
});
where R.drawable.ic_error
=
保持文本为空可以解决问题
但如果我们在 setError(null) 中只保留 null,则不会显示验证错误;它应该与第二个参数一起为空。