1


I had an EditText for which I added left n right drawable. I am unable to handle click evnt for right drwable . How to handle click events for android right drawable icon.

user1276092
  • 523
  • 3
  • 8
  • 30
  • 1
    Post your code..without code its hard to say anything. – Hamid Shatu Mar 24 '14 at 14:44
  • 2
    possible duplicate of [Handling click events on a drawable within an EditText](http://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittext) – Bryan Herbst Mar 24 '14 at 14:45

3 Answers3

3

you need to add touchevent replace onclick and you can use below code

mEditTextSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length()>0){
            mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(android.R.drawable.ic_delete), null);
        }else{
            mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.abc_ic_search), null);
        }
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void afterTextChanged(Editable s) {
    }
});
mEditTextSearch.setOnTouchListener(new OnTouchListener() {
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(mEditTextSearch.getCompoundDrawables()[2]!=null){
                if(event.getX() >= (mEditTextSearch.getRight()- mEditTextSearch.getLeft() - mEditTextSearch.getCompoundDrawables()[2].getBounds().width())) {
                    mEditTextSearch.setText("");
                }
            }
        }
        return false;
    }
});
varotariya vajsi
  • 3,965
  • 37
  • 39
0

I don't think you can handle an event for leftDrawable or rightDrawable. You can handle events for the whole view. If you want to do this you have two choices:

  • Extend your own version of EditText or
  • Put your drawable as an independent ImageView
Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
0

as in: Handling click events on a drawable within an EditText

editComment.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, 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() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))
            {
                // your action here

             return true;
            }
        }
        return false;
    }
});
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Hossein Moghimi
  • 409
  • 5
  • 5