问题
I have an EditText with a drawable inside. I want to make the drawable clickable so that I can have a specific action when user clicks the drawable. How do I do that? My EditText is:
<EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:drawableRight="@drawable/question_mark"
android:hint="phone number"
android:imeActionId="@+id/phone_num"
android:maxLines="1"
android:singleLine="true"
android:textColor="#000000" />
回答1:
As Gina suggested above, you can achieve this by using RelativeLayout instead of drawableRight property. Code below puts the imageview to the right part of your EditText
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:hint="phone number"
android:imeActionId="@+id/phone_num"
android:maxLines="1"
android:singleLine="true"
android:textColor="#000000" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignRight="@+id/phone"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
回答2:
phone.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
final int DRAWABLE_RIGHT = 2;
if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
if(motionEvent.getRawX() >= (phone.getRight() - phone.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
//Here is your code when you click drawable right
return true;
}
}
return false;
}
});
来源:https://stackoverflow.com/questions/17558072/clickable-drawable-inside-edittext-in-android