標籤:test round ontouch content idt 區別 布局 listen get
使用情境
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); } });
Android EditText+ListPopupWindow實現可編輯的下拉式清單