EditText setError() 带图标但不带弹出消息

2023-12-10

I want to to have some validation for my EditText wherein I want to show "enter image description here" icon (that comes when you put editText.setError("blah blah")) but don't want the text in the popup displaying that "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 中的视图,如下所示-

<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,则不会显示验证错误;它应该与第二个参数一起为空。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

EditText setError() 带图标但不带弹出消息 的相关文章

随机推荐