处理点击事件上绘制一个EditText内事件、EditText

2023-09-11 11:48:27 作者:爷们霸气十足i

我添加在的EditText 插件的文本图像的权利,使用下面的XML:

I have added an image right of the text in an EditText widget, using the following XML:

<EditText
  android:id="@+id/txtsearch"
  ...
  android:layout_gravity="center_vertical"
  android:background="@layout/shape"
  android:hint="Enter place,city,state"
  android:drawableRight="@drawable/cross" />

不过,我想清楚了的EditText 嵌入图像被点击时。我怎样才能做到这一点?

But I want to clear the EditText when the embedded image is clicked. How can I do this?

推荐答案

其实你不需要扩展任何类。比方说,我有一个EditText editComment与drawableRight

Actually you don't need to extend any class. Let's say I have an EditText editComment with a drawableRight

    editComment.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() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here

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

我们在 getRawX(),因为我们希望得到的触摸屏幕上的实际位置,而不是相对于父。

we getRawX() because we want to get the actual position of touch on screen, not relative to parent.

要获得左侧点击

if(event.getRawX() <= (editComment.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width()))