Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add OnClickListener to Drawable in EditText?

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

});

??

like image 798
Denis Gubert Avatar asked Dec 21 '13 22:12

Denis Gubert


1 Answers

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>
like image 104
GareginSargsyan Avatar answered Sep 19 '22 16:09

GareginSargsyan