仿微信password控件,实现密码可见于不可见功能

1、控件源码VisiblePasswordEditText .java

package cn.com.dsyc.canteenappforseller.widget;

import cn.com.dsyc.canteenappforseller.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

public class VisiblePasswordEditText extends EditText {

	private Drawable mPasswordShow;
	private Drawable mPasswordHide;
	private boolean mHide = true;

	public VisiblePasswordEditText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		if (!isInEditMode())
			init();
	}

	public VisiblePasswordEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		if (!isInEditMode())
			init();
	}

	public VisiblePasswordEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		if (!isInEditMode())
			init();
	}

	
	private void init()
	{
		mPasswordShow = getResources().getDrawable(R.drawable.password_show);
		mPasswordHide = getResources().getDrawable(R.drawable.password_hide);
		mPasswordShow.setBounds(0, 0, mPasswordShow.getIntrinsicWidth(), mPasswordShow.getIntrinsicHeight());
		mPasswordHide.setBounds(0, 0, mPasswordHide.getIntrinsicWidth(), mPasswordHide.getIntrinsicHeight());
		setHeight(mPasswordHide.getIntrinsicHeight() + getResources().getDimensionPixelSize(R.dimen.one_dp_padding) * 5);
		update();
		
		setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (getCompoundDrawables()[2] != null) {
					if (event.getAction() == MotionEvent.ACTION_UP && event.getX() > getWidth() - getPaddingRight() - mPasswordHide.getIntrinsicWidth()) {
						mHide = !mHide;
						update();
					}
				}
				return false;
			}
		});

	}

	private void update() {
		Drawable[] drawables = getCompoundDrawables();
		if (mHide) {
			setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
			setCompoundDrawables(drawables[0], drawables[1], mPasswordHide, drawables[3]);
		} else {
			setInputType(EditorInfo.TYPE_CLASS_TEXT);
			setCompoundDrawables(drawables[0], drawables[1], mPasswordShow, drawables[3]);
		}
		setSelection(getText().length());
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值