我已经在EditText小部件中添加了文本右侧的图像,使用以下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。我该怎么做呢?
非常非常好,感谢所有参与讨论的人。因此,如果你不想处理扩展类带来的不便,你可以执行以下操作(仅为正确的可绘制对象实现)
this.keyword = (AutoCompleteTextView) findViewById(R.id.search);
this.keyword.setOnTouchListener(new RightDrawableOnTouchListener(keyword) {
@Override
public boolean onDrawableTouch(final MotionEvent event) {
return onClickSearch(keyword,event);
}
});
private boolean onClickSearch(final View view, MotionEvent event) {
// do something
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
下面是基于@Mark的回答的基本侦听器实现
public abstract class RightDrawableOnTouchListener implements OnTouchListener {
Drawable drawable;
private int fuzz = 10;
/**
* @param keyword
*/
public RightDrawableOnTouchListener(TextView view) {
super();
final Drawable[] drawables = view.getCompoundDrawables();
if (drawables != null && drawables.length == 4)
this.drawable = drawables[2];
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@Override
public boolean onTouch(final View v, final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && drawable != null) {
final int x = (int) event.getX();
final int y = (int) event.getY();
final Rect bounds = drawable.getBounds();
if (x >= (v.getRight() - bounds.width() - fuzz) && x <= (v.getRight() - v.getPaddingRight() + fuzz)
&& y >= (v.getPaddingTop() - fuzz) && y <= (v.getHeight() - v.getPaddingBottom()) + fuzz) {
return onDrawableTouch(event);
}
}
return false;
}
public abstract boolean onDrawableTouch(final MotionEvent event);
}
我创建了一个简单的自定义触摸侦听器类,而不是自定义EditText
public class MyTouchListener implements View.OnTouchListener {
private EditText editText;
public MyTouchListener(EditText editText) {
this.editText = editText;
setupDrawable(this.editText);
}
private void setupDrawable(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>0)
editText.setCompoundDrawablesWithIntrinsicBounds(0,0, R.drawable.clearicon,0);
else
editText.setCompoundDrawablesWithIntrinsicBounds(0,0, 0,0);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(editText.getCompoundDrawables()[2]!=null){
if(event.getX() >= (editText.getRight()- editText.getLeft() - editText.getCompoundDrawables()[2].getBounds().width())) {
editText.setText("");
}
}
}
return false;
}
}
当EditText为空白时,将没有可绘制对象。绘图将显示我们开始编辑以清除EditText的时间。
你可以设置触摸监听器
mEditText.setOnTouchListener(new MyTouchListener(mEditText));