Reputation:
Is it possible to add a OnClickListener
to on a drawable that is declared in designer as drawableleft
android:drawableLeft="@drawable/ic_password"
Or is there any way to add a ImageView
on the left side of that EditText
Upvotes: 7
Views: 14281
Reputation: 1352
You need to implement the OnTouchListener and add your click action.
I used the below helper class. onDrawableClick
returns:
true if the listener has consumed the event, false otherwise
public abstract class DrawableClickListener implements View.OnTouchListener {
public static final int DRAWABLE_LEFT = 0;
public static final int DRAWABLE_TOP = 1;
public static final int DRAWABLE_RIGHT = 2;
public static final int DRAWABLE_BOTTOM = 3;
private final int drawableIndex;
public DrawableClickListener(int index) {
drawableIndex = index;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
TextView textView = (TextView) view;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (textView.getRight() - textView.getCompoundDrawables()[drawableIndex].getBounds().width())) {
return onDrawableClick();
}
}
return false;
}
public abstract boolean onDrawableClick();
}
Upvotes: 0
Reputation: 6087
There is more elegant way:
Don't use android:drawableStart
or android:drawableLeft
in the TextInputEditText
.
Instead you can use:
<com.google.android.material.textfield.TextInputLayout
...
app:endIconMode="custom"
app:startIconDrawable="@drawable/..."
and then use the endIconOnClickListener
:
textInputLayout.setStartIconOnClickListener {
// Respond to end icon presses
}
Source: https://stackoverflow.com/a/65940540/13545849
Upvotes: 1
Reputation: 885
You can achieve it by a RelativeLayout:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<ImageView
android:id="@+id/image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:src="@drawable/ic_iamge"/>
<EditText
android:id="@+id/text_id"
android:layout_toRightOf="@id/image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="16dp"
android:text="Your text" />
</RelativeLayout>
And add onClickListener
to the ImageView
in your code.
Upvotes: 0