使用场景
AutoCompleteEditText只有开始输入并且与输入的字符有匹配的时候才弹出下拉列表.Spinner的缺点是不可以编辑.所以本文介绍如何使用EditText+ListPopupWindow实现可编辑的下拉列表.使用场景可以是有记住密码功能的登录框.
给EditText增加上下箭头
我们需要一个箭头图片,放在EditText的右面,用来点击后弹出下拉列表.如图所示
要想实现这个很容易,只需要在布局文件中给EditText设置一个drawableRight的属性.
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableRight="@drawable/pull_down1"/>
如何在点击的时候切换箭头的方向
切换箭头的上下方向,实际上就是重新设置EditText的drawableRight.这就需要动态的设置EditText的drawableRight.
setCompoundDrawables(left, top, right, bottom); setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
意思是设置Drawable显示在text的左、上、右、下位置。
但是两者有些区别:
setCompoundDrawables 画的drawable的宽高是按drawable.setBound()设置的宽高,所以才有The Drawables must already have had setBounds(Rect) called.意思是说使用之前必须使用Drawable.setBounds设置Drawable的长宽。
而setCompoundDrawablesWithIntrinsicBounds是画的drawable的宽高是按drawable固定的宽高,即通过getIntrinsicWidth()与getIntrinsicHeight()获得,所以才有The Drawables’ bounds will be set to their intrinsic bounds.这句话之说!
例如:
editTest.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.test), null, null, null);
给EditText添加触摸监听事件,当点击到drawableRight部位的时候,就重新设置图片资源
editText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getX() >= (editText.getWidth() - editText .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { // your action here editText.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.pull_up1), null); return true; } } return false; } });
ListPopupWindow
最后一步就是显示列表了
private void showListPopulWindow(){ String[] list = { "item1", "item2", "item3", "item4" }; listPopupWindow = new ListPopupWindow(this); listPopupWindow.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list)); listPopupWindow.setAnchorView(editText); listPopupWindow.setModal(true); listPopupWindow.show(); }
可以给listPopupWindow 设置监听事件,当item被选择的时候干啥,当listPopupWindow消失的时候干啥
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { editText.setText(list[i]); } }); listPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { editText.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.pull_down1), null); } });