如何在TextInputEditText
的复合吸引物上检测单击事件?
使用以下TextInputEditText
的Overriden版本,然后致电setOnDrawableClickedListener
。
,如果您在编辑文本的末尾设置可绘制的绘制可能会比开始时更好,因为当前版本的TextInputLayout
版本会在一开始时产生相当丑陋的结果。
样品布局将进一步下降。(特别注意android:drawablePadding="10dp"
的使用)。
代码适用于Androidx,但您可以琐碎地回到AppCompat。
package com.twoplay.netplayer.controls;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.textfield.TextInputEditText;
public class TextInputEditTextEx extends TextInputEditText {
private OnDrawableClickedListener onDrawableClickedListener;
public TextInputEditTextEx(Context context) {
super(context);
init();
}
public TextInputEditTextEx(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TextInputEditTextEx(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOnTouchListener(new OnTouchListener() {
private Rect hitBounds = new Rect();
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int hitDrawable = -1;
if (x < getCompoundPaddingLeft())
{
hitDrawable = 0;
hitBounds.set(0,0,getCompoundPaddingLeft(),getHeight());
}
if (x > getWidth()-getCompoundPaddingRight())
{
hitDrawable = 2;
hitBounds.set(getCompoundPaddingRight(),0,getWidth(),getHeight());
}
if (hitDrawable != -1)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_UP)
{
onDrawableClicked(hitDrawable,hitBounds);
}
return true;
}
return false;
}
});
}
private void onDrawableClicked(int i, Rect bounds) {
if (onDrawableClickedListener != null)
{
onDrawableClickedListener.onDrawableClicked(this,i,bounds);
}
}
public interface OnDrawableClickedListener {
void onDrawableClicked(View v, int drawable, Rect bounds);
}
public void setOnDrawableClickedListener(OnDrawableClickedListener listener)
{
this.onDrawableClickedListener = listener;
}
}
样本布局:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/playlist_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/playlist_name" >
<com.twoplay.netplayer.controls.TextInputEditTextEx
android:id="@+id/playlist_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:drawableEnd="@drawable/ic_more_horiz_black_24dp"
android:drawablePadding="10dp" />
</com.google.android.material.textfield.TextInputLayout>