Android 文字框,編輯框裡的圖片點選事件
阿新 • • 發佈:2019-01-30
這個方法是通用的,不僅僅適用於EditText,也適用於TextView、AutoCompleteTextView等控制元件。
Google官方API並沒有給出一個直接的方法用來設定右邊圖片的點選事件,所以這裡我們需要通過點選位置來判斷點選事件
今天來設定右邊清空的簡單邏輯
android:drawableRight="@mipmap/quxiaox"在Activity中:
ed_search=(EditText)findViewById(R.id.ed_search);先獲取例項;
//右邊圖片的點選事件 ed_search.setOnTouchListener(new View.OnTouchListener() { @Overridepublic boolean onTouch(View v, MotionEvent event) { //ed_search.getCompoundDrawables()[4]; 得到一個長度為4的陣列,分別表示左右上下的四張圖 Drawable drawable=ed_search.getCompoundDrawables()[2]; //如果右邊沒有圖片,不再處理 if(drawable ==null){ return false; } //如果不是按下事件,不再處理 if(event.getAction()!=MotionEvent.ACTION_UP){ return false; } if(event.getX()>ed_search.getWidth()-ed_search.getPaddingRight()-drawable.getIntrinsicWidth()){ ed_search.setText(" "); } return false; } });