这个方法是通用的,不仅仅适用于EditText,也适用于TextView、AutoCompleteTextView等控件。
Google官方API并没有给出一个直接的方法用来设置右边图片的点击事件,所以这里我们需要通过点击位置来判断点击事件
今天来设置右边清空的简单逻辑
android:drawableRight="@mipmap/quxiaox"在Activity中:
ed_search=(EditText)findViewById(R.id.ed_search);先获取实例;
//右边图片的点击事件 ed_search.setOnTouchListener(new View.OnTouchListener() { @Override public 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; } });