点击右侧图片后的效果图:
代码实现:
1. activity_main:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<AutoCompleteTextView
android:id="@+id/auto_complete_text_view"
style="?android:editTextStyle"
android:layout_width="match_parent"
android:layout_height="56dp"
android:completionThreshold="1"
android:drawableEnd="@android:drawable/ic_delete"
android:editable="true"
android:singleLine="true"/>
</LinearLayout>
2. MainActivity
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements View.OnTouchListener {
private List<String> mData = new ArrayList<>();
{
for (int i = 0; i < 15; i++) {
mData.add("item: " + i);
}
for (int i = 0; i < 15; i++) {
mData.add("tttt: " + i);
}
}
private AutoCompleteTextView mAutoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.auto_complete_text_view);
mAutoCompleteTextView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mData));
mAutoCompleteTextView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// getCompoundDrawablesRelative() 可以获取一个长度为4的数组,
// 存放drawableStart,Top,End, Bottom四个图片资源对象
// index=2 表示的是 drawableEnd 图片资源对象
Drawable drawable = mAutoCompleteTextView.getCompoundDrawablesRelative()[2];
if (drawable == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
// drawable.getIntrinsicWidth() 获取drawable资源图片呈现的宽度
if (event.getX() > mAutoCompleteTextView.getWidth() - mAutoCompleteTextView.getPaddingRight()
- drawable.getIntrinsicWidth()) {
// 进入这表示图片被选中,可以处理相应的逻辑了
mAutoCompleteTextView.showDropDown();
}
return false;
}
}
注意在 activity_main 中 AutoCompleteTextView 使用的 style 是 android:editTextStyle,同时设置了 android:editable:true。
简单方式实现可下拉的EditText