我已经在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。我该怎么做呢?
我创建了一个简单的自定义触摸侦听器类,而不是自定义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));
还有更优雅的方式:
不要在TextInputEditText中使用android:drawableRight或android:drawableEnd。
相反,你可以用:
<com.google.android.material.textfield.TextInputLayout
...
app:endIconMode="custom"
app:endIconDrawable="@drawable/..."
然后使用endIconOnClickListener:
textInputLayout.setEndIconOnClickListener {
// Respond to end icon presses
}
来源:https://stackoverflow.com/a/65940540/13545849