我已经在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));
我已经采取了@AZ_的解决方案,并将其转换为kotlin扩展函数:
所以在代码中复制这个:
@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
this.setOnTouchListener(View.OnTouchListener { _, event ->
val DRAWABLE_LEFT = 0
val DRAWABLE_TOP = 1
val DRAWABLE_RIGHT = 2
val DRAWABLE_BOTTOM = 3
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
) {
setClickListener()
return@OnTouchListener true
}
}
false
})
}
你可以在EditText上调用setDrawableRightTouch函数来使用它:
yourEditText.setDrawableRightTouch {
//your code
}
这么多的解决方案,但没有一个适合我,当我有两个连续的领域。
这是添加清除按钮编辑文本的解决方案,在我有两个字段或一行中的一个字段的情况下为我工作。用kotlin写的!
@SuppressLint("PrivateResource")
fun <T : EditText> T.withClear(): T {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable) {
setCompoundDrawablesWithIntrinsicBounds(0, 0,
if (editable.isNotEmpty()) abc_ic_clear_material else 0, 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
})
setOnTouchListener { _, event ->
if (event.action == ACTION_UP && event.x >= (right - this.compoundPaddingRight)) {
setText("")
return@setOnTouchListener true
}
false
}
return this
}