使用 drawable 清除 editText 字段

Clear editText field wth drawable

我有一个自动完成的 editText 字段,我发现这段代码用于清除 editText 字段上的文本并将其放在该字段的右上角,我的问题是在我清除 editText 字段上的文本一次后,十字(可绘制)消失。我必须离开页面并再次返回才能再次看到它。我怎样才能让它一直可见?请帮忙。 这是我的代码:

 String value = "";
    personAccountableAutoCompleteTextView.setText(value);
    final Drawable x = getResources().getDrawable(R.drawable.clear);
    personAccountableAutoCompleteTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (personAccountableAutoCompleteTextView.getCompoundDrawables()[2] == null) {
                return false;
            }

            if (event.getX() > personAccountableAutoCompleteTextView.getWidth() - personAccountableAutoCompleteTextView.getPaddingRight() - x.getIntrinsicWidth()) {
                personAccountableAutoCompleteTextView.setText("");
                x.setVisible(true,true);
                personAccountableAutoCompleteTextView.setCompoundDrawables(null, null, null, null);
            }
            return false;
        }
    });

像这样在 xml 中赋予您的 edittext 可绘制权限:

<EditText
  android:layoutheight="wrap_content"
  android:layoutwidth="match_parent"
  android:drawableright="@drawable/yourimg"/>

然后将 onclicklistener 提供给该可绘制对象,如下所示:

edittext.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() >= (edittext.getRight() - edittext.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here

                 return true;
                }
            }
            return false;
        }
    });