我已经在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。我该怎么做呢?
考虑以下几点。这不是最优雅的解决方案,但它是有效的,我刚刚测试过。
Create a customized EditText class CustomEditText.java:
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
public class CustomEditText extends EditText
{
private Drawable dRight;
private Rect rBounds;
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
@Override
public void setCompoundDrawables(Drawable left, Drawable top,
Drawable right, Drawable bottom)
{
if(right !=null)
{
dRight = right;
}
super.setCompoundDrawables(left, top, right, bottom);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_UP && dRight!=null)
{
rBounds = dRight.getBounds();
final int x = (int)event.getX();
final int y = (int)event.getY();
//System.out.println("x:/y: "+x+"/"+y);
//System.out.println("bounds: "+bounds.left+"/"+bounds.right+"/"+bounds.top+"/"+bounds.bottom);
//check to make sure the touch event was within the bounds of the drawable
if(x>=(this.getRight()-rBounds.width()) && x<=(this.getRight()-this.getPaddingRight())
&& y>=this.getPaddingTop() && y<=(this.getHeight()-this.getPaddingBottom()))
{
//System.out.println("touch");
this.setText("");
event.setAction(MotionEvent.ACTION_CANCEL);//use this to prevent the keyboard from coming up
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable
{
dRight = null;
rBounds = null;
super.finalize();
}
}
Change your layout XML to this (where com.example is your actual project package name):
<com.example.CustomEditText
android:id="@+id/txtsearch"
…
android:layout_gravity="center_vertical"
android:background="@layout/shape"
android:hint="Enter place,city,state"
android:drawableRight="@drawable/cross"
/>
Finally, add this (or something similar) to your activity:
…
CustomEditText et = (CustomEditText) this.findViewById(R.id.txtsearch);
…
我可能在计算嵌套drawable的触摸边界时有点出错,但你懂的。
我希望这能有所帮助。
还有更优雅的方式:
不要在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