user1276092
user1276092

Reputation: 513

Click event for Android EditText Right Drawable


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.

Upvotes: 1

Views: 6243

Answers (3)

Hossein Moghimi
Hossein Moghimi

Reputation: 409

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;
    }
});

Upvotes: 0

varotariya vajsi
varotariya vajsi

Reputation: 4041

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;
    }
});

Upvotes: 3

Sebastian Breit
Sebastian Breit

Reputation: 6159

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

Upvotes: 0

Related Questions