Android的TextView有个DrawableLeft和DrawableRight属性,UI布局中经常会用到。比如登陆界面,用户名和密码前面的图像,就是用DrawableLeft来设置的。
但比较郁闷的是,android并没有为DrawableLeft和DrawableRight提供监听点击事件的api,但这个需求是很常见的,比如输入密码的时候,点击右边的眼睛,密码变为明文。
其实思路很简单,我们只要重写EditText的onTouchEvent,捕捉到点击事件,然后判断用户点击的位置是否点击到图标即可,不废话,用代码说话。
1、添加XTextView类继承自TextView
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class XTextView extends android.support.v7.widget.AppCompatTextView {
private DrawableLeftListener mLeftListener;
private DrawableRightListener mRightListener;
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
public XTextView(Context context) {
super(context);
}
public XTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public XTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setDrawableLeftListener(DrawableLeftListener listener) {
this.mLeftListener = listener;
}
public void setDrawableRightListener(DrawableRightListener listener) {
this.mRightListener = listener;
}
public interface DrawableLeftListener {
public void onDrawableLeftClick(View view);
}
public interface DrawableRightListener {
public void onDrawableRightClick(View view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mRightListener != null) {
Drawable drawableRight = getCompoundDrawables()[DRAWABLE_RIGHT];
if (drawableRight != null && event.getRawX() >= (getRight() - drawableRight.getBounds().width())) {
mRightListener.onDrawableRightClick(this);
return true;
}
}
if (mLeftListener != null) {
Drawable drawableLeft = getCompoundDrawables()[DRAWABLE_LEFT];
if (drawableLeft != null && event.getRawX() <= (getLeft() + drawableLeft.getBounds().width()))
mLeftListener.onDrawableLeftClick(this);
return true;
}
break;
}
return super.onTouchEvent(event);
}
}
2、layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.term.paimai.helper.XTextView
android:id="@+id/login_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin_normal"
android:drawableLeft="@mipmap/ic_tab_triangle_left"
android:text="@string/login"
android:textAlignment="center"
android:textSize="@dimen/text_size_large"/>
3、activity添加点击响应
xtvLoginBack.setDrawableLeftListener(new XTextView.DrawableLeftListener() {
@Override
public void onDrawableLeftClick(View view) {
onBackPressed();
}
});
参考: