我已经在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。我该怎么做呢?
还有更优雅的方式:
不要在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
上述问题的一个可能的解决方案是使用android的新材质组件TextInputLayout。
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/searchInput"
style="@style/Widget.App.TextInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
app:endIconMode="custom"
app:endIconContentDescription="Search"
app:endIconDrawable="@drawable/ic_search">
<EditText
android:id="@+id/et_search"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.google.android.material.textfield.TextInputLayout>
在这里设置TextInputLayout属性endIconMode时,将一个按钮放置在所包含的EditText的末尾。
另外app:endIconMode = "custom"允许自定义图标的点击功能
最后,为了监听结束图标单击,调用外围TextInputLayout组件上的setEndIconClickListener()。
Kotlin是一种很棒的语言,每个类都可以使用新方法进行扩展。让我们为EditText类介绍一个新方法,它将捕捉点击到右绘图。
fun EditText.onRightDrawableClicked(onClicked: (view: EditText) -> Unit) {
this.setOnTouchListener { v, event ->
var hasConsumed = false
if (v is EditText) {
if (event.x >= v.width - v.totalPaddingRight) {
if (event.action == MotionEvent.ACTION_UP) {
onClicked(this)
}
hasConsumed = true
}
}
hasConsumed
}
}
你可以看到它以回调函数作为参数,当用户单击右可绘制时调用。
val username = findViewById<EditText>(R.id.username_text)
username.onRightDrawableClicked {
it.text.clear()
}