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

Android 设置DrawableRight和DrawableLeft 点击事件

2015-12-09 15:06 465 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">package com.ulucu.xview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
* Created by lbin on 2015/12/9.
*/
public class XEditText extends EditText {

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 XEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}

public XEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public XEditText(Context context) {
super(context);
}

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_UP:
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);
}
}



<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">然后可以写一个自定义监听类。</span>


private class DrawableRightClickListener implements XEditText.DrawableRightListener {

@Override
public void onDrawableRightClick(View view) {
if (!mIsShow) {
network_password.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_password, 0, R.mipmap.btn_nosee, 0) ;
network_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ;
} else {
network_password.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_password, 0, R.mipmap.btn_see, 0) ;
network_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) ;
}

mIsShow = !mIsShow ;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: