一:适用于EditText、TextView等控件,通过点击位置来控制点击事件
布局文件:
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@drawable/guanbi"
android:layout_centerVertical="true"/>
调用:
EditText edit = (EditText) this.findViewById(R.id.edit);
edit.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// edit.getCompoundDrawables()得到一个长度为4的数组,分别表示左右上下四张图片
Drawable drawable = edit.getCompoundDrawables()[2];
// 右边有图片
if (drawable != null) {
// 是点击事件
if (event.getAction() == MotionEvent.ACTION_UP) {
// 手指按下位置在图片内
if (event.getX() > edit.getWidth() - edit.getPaddingRight() - drawable.getIntrinsicWidth()){
edit.setText("");
}
}
}
return false;
}
});
二:使用自定义EditText
自定义EditText——EditTextImage
package com.example.test.tools;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.appcompat.widget.AppCompatEditText;
public class EditTextImage extends AppCompatEditText {
private onDrawableRightListener rightListener;
final int DRAWABLE_RIGHT = 2;
public EditTextImage(Context context) {
super(context);
}
public EditTextImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditTextImage(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 绑定监听事件
*/
public void setDrawableRightListener(onDrawableRightListener listener) {
this.rightListener = listener;
}
/**
* 监听回调接口
*/
public interface onDrawableRightListener {
void onDrawableRightClick(View view);
}
/**
* 判断点击的位置是否是右侧图标,如果是则执行相应的回调函数
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (rightListener != null) {
Drawable drawable = getCompoundDrawables()[DRAWABLE_RIGHT];
if (drawable != null && event.getRawX() >= (getRight() - drawable.getBounds().width())) {
rightListener.onDrawableRightClick(this);
}
}
break;
}
return super.onTouchEvent(event);
}
}
布局文件:
<com.example.test.tools.EditTextImage
android:id="@+id/edit_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edit"
android:layout_marginTop="30dp"/>
调用:
EditTextImage edit_image = findViewById(R.id.edit_image);
// 设置图标大小、位置
Drawable drawable = getResources().getDrawable(R.drawable.guanbi);
drawable.setBounds(0, 0, 100, 100);
edit_image.setCompoundDrawables(null, null, drawable, null);
edit_image.setDrawableRightListener(new EditTextImage.onDrawableRightListener() {
@Override
public void onDrawableRightClick(View view) {
edit_image.setText("");
}
});