我已经在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。我该怎么做呢?
上述问题的一个可能的解决方案是使用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()。
这对我很有用,
mEditTextSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>0){
mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(android.R.drawable.ic_delete), null);
}else{
mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.abc_ic_search), null);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
mEditTextSearch.setOnTouchListener(new OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(mEditTextSearch.getCompoundDrawables()[2]!=null){
if(event.getX() >= (mEditTextSearch.getRight()- mEditTextSearch.getLeft() - mEditTextSearch.getCompoundDrawables()[2].getBounds().width())) {
mEditTextSearch.setText("");
}
}
}
return false;
}
});