参考:
http://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittext
本例以 drawableRight 为例,其它类似。
思路:
重写EditText的OnTouchListener事件,在up事件中判断手指的位置,如果在drawableRight 范围内,就当作drawableRight的click事件。
1,xml中添加drawableRight
1 <EditText 2 android:id="@+id/search" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:gravity="center_horizontal" 6 android:hint="digits=0123456789" 7 android:drawableRight="@drawable/ic_clear_search_api_holo_light" 8 android:imeActionLabel="send" 9 android:imeOptions="actionSend|flagNoExtractUi" 10 android:inputType="text" />
2,代码中:
变量声明,初始化等。
public class MainActivity extends AppCompatActivity { EditText search; ... }
定义OnTouchListener事件
1 View.OnTouchListener touchListener = new View.OnTouchListener(){ 2 @Override 3 public boolean onTouch(View v, MotionEvent event) { 4 5 //只有当手指在rightDrawable区域时,才return true 表示已经处理事件,其它return false表示由框架处理。 6 if(event.getRawX() >= (search.getRight() - search.getCompoundDrawables()[2].getBounds().width())) { 7 8 System.out.println(event);//打印事件 9 10 //手指在rightDrawable区域时并且是 MotionEvent.ACTION_UP时才去实现点击rightDrawable事件代码。 11 //MotionEvent.ACTION_DOWN,MotionEvent.ACTION_MOVE 跳过。 12 13 if(event.getAction() == MotionEvent.ACTION_UP) { 14 // your action here 15 search.requestFocus();//如果此时search没有焦点,要申请下。 16 showEmotion();//你的方法 17 } 18 return true;//表示事件在这里已经处理,不会继续传。 19 } 20 return false;//表示由框架处理,那么会有edit的行为,如粘贴等。 21 } 22 };
给EditText设置OnTouchListener
1 search.setOnTouchListener(touchListener);