我想对我的EditText进行一些验证,其中我想显示“android - 带图标但没有弹出消息的EditText setError()-LMLPHP”图标(当您将editText.setError("blah blah"))放入但不希望弹出窗口中显示“blah blah”的文本时出现。

有什么办法吗?一种方法是创建一个自定义布局,该布局将在EditText中显示图像图标。但是还有更好的解决方案吗?

最佳答案

经过大量研究和排列后问题得以解决-(还要感谢@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中的 View -
<com.raj.poc.MyEditText
    android:id="@+id/et_test"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

现在,在第三步中,只需将TextWatcher设置为您的自定义文本 View ,如下所示-
    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);
            }
        }
    });

其中R.drawable.ic_error =

保持文本为空即可解决问题
但是,如果我们在setError(null)中仅保留null,则不会显示验证错误。与第二个参数一起应为null。

10-07 19:36
查看更多