How can I add OnClickListener to Drawable in EditText?

Denis Gubert picture Denis Gubert · Dec 21, 2013 · Viewed 10.7k times · Source

I have edittext and want to add to right "search" icon..

searchTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.search, 0);

But how can I add event for click this icon?

searchTxt.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
    Drawable co = ((TextView) v).getCompoundDrawables()[2];

    if (event.getX() > v.getMeasuredWidth() - v.getPaddingRight()
                     - co.getIntrinsicWidth()) {
        Datas.search = searchTxt.getText().toString();
            startActivity(Search.class);
        return true;
    } else {
        return false;
    }
    }

});

??

Answer

GareginSargsyan picture GareginSargsyan · Dec 22, 2013

Drawables are non-interactive elements, so you cannont set a click listener on a drawable. A simple solution would be putting an ImageView containing the "search" icon over the EditText and adding a right padding on the EditText so the text doesn't overlap with the icon.

<FrameLayout android:layout_width="wrap_content"
             android:layout_height="wrap_content">
    <EditText ...
              android:paddingRight="..."
              ... />
    <ImageView ...
               android:src="@drawable/search"
               android:layout_gravity="right|center_vertical"
               ... />
</FrameLayout>