您的位置:首页 > 移动开发 > Android开发

Android 设置DrawableRight和DrawableLeft点击事件

2017-06-28 16:03 357 查看
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();
}
});

参考:

http://blog.csdn.net/tom_xiaoxie/article/details/50771763
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: