zoukankan      html  css  js  c++  java
  • Android自定义控件实现带有清除按钮的EditText

    首先声明我也是参考了别人的思路,只是稍微做了下修改,增加显示密码与隐藏密码,没有输入字符串时让EditText进行抖动,废话少说这里附上效果图

    效果很赞有木有

    那么怎么实现这种效果呢?那就跟着我一起来吧

    首先我们先分析一下清除功能怎么实现的,我们怎么知道用户点击的是清除按钮还是别的地方呢?,而EditText其实是集成Textview的,

    而Textview有方法getTotalPaddingRight()获取图标左边缘至控件右边缘的距离,知道这样一个方法之后就很简单了,如下图所示我们就可以得到用户是不是点击的清除按钮图标,得到之后我们

    只要设置setText("")不就实现了清除功能吗?

    还有一个重要的问题就是EditText其实没有很好的点击事件,我们如果知道用户点击了并且点击的是清除按钮的位置,所以我们需要知道用户点击还是没有点击,而这个问题我们就可以通过View的onTouchEvent方法

    都知道这个方法是用户触摸事件,所以我们只用户抬起屏幕不就相当于点击了么,ok!重要思路知道了之后我们就可以开始愉快的代码变成喽!

    首先我们需要先自定义一个类去继承EditText类,重写里面的三个构造方法

    public class ClearEditText extends EditText implements  
            OnFocusChangeListener, TextWatcher { 
    
       public ClearEditText(Context context) { 
            this(context, null); 
        } 
     
        public ClearEditText(Context context, AttributeSet attrs) { 
            //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
            this(context, attrs, android.R.attr.editTextStyle); 
        } 
        
        public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();//这个方法主要是初始化工作,比如将清除按钮画上去
        } 
    } 
    init();//这个方法主要是初始化工作,比如将清除按钮画上去,
    getCompoundDrawables()获取Drawable的四个位置的数组,四个位置为左上右下
    setBounds()设置图片的位置以及大小,
    其中getIntrinsicWidth()很重要,我们要画图片的宽度,首先就要知道图片的宽度,这个方法是获取显示出来的宽度而不是图片实际的宽度,高度是一样的道理
    private void init() { 
            //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,getCompoundDrawables()获取Drawable的四个位置的数组
            mClearDrawable = getCompoundDrawables()[2]; 
            if (mClearDrawable == null) {
                mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
    //            throw new NullPointerException("You can add drawableRight attribute in XML");
            } 
            //设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
            mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); 
            //默认设置隐藏图标
            setClearIconVisible(false); 
            //设置焦点改变的监听
            setOnFocusChangeListener(this); 
            //设置输入框里面内容发生改变的监听
            addTextChangedListener(this); 
        } 
    
    

      图片画上去之后我们就开始重写onTouchEvent这个方法,其中怎么判断位置是清除按钮图标的位置我上面已经讲过了,而且原理图也有,大家应该好理解,

    boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
    						&& (event.getX() < ((getWidth() - getPaddingRight())));
    				
    				if (touchable) {
    					this.setText("");
    				}可以看到如果正好是清除按钮的位置我们就调用setText方法赋值一个空字符达到清除的目的
    public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (getCompoundDrawables()[2] != null) {
                    //getTotalPaddingRight()图标左边缘至控件右边缘的距离
                    //getWidth() - getTotalPaddingRight()表示从最左边到图标左边缘的位置
                    //getWidth() - getPaddingRight()表示最左边到图标右边缘的位置
                    boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                            && (event.getX() < ((getWidth() - getPaddingRight())));
                    
                    if (touchable) {
                        this.setText("");
                    }
                }
    //            if(getCompoundDrawables()[0] != null){
    //                boolean touchLeft = event.getX()>0 && event.getX()<getCompoundDrawables()[0].getIntrinsicWidth();
    //                if(touchLeft){
    //                    if(isShow==false){
    //                        isShow = true;
    //                        //设置为可见
    //                        this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    //                    }else{
    //                        isShow = false;
    //                        //设置为密码模式
    //                        this.setTransformationMethod(PasswordTransformationMethod.getInstance());
    //                    }
    //                }
    //            }
            }
    
            return super.onTouchEvent(event);
        }

      再就是EditText的晃动动画了

    public static Animation shakeAnimation(int counts){
            Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
            translateAnimation.setInterpolator(new CycleInterpolator(counts));
            translateAnimation.setDuration(1000);
            return translateAnimation;
        }

      再就是怎么去显示我们的密码,和怎么将光标放到字符串最后一个位置上

    //密码设置为可见
    setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    //密码设置为不可见
    setTransformationMethod(PasswordTransformationMethod.getInstance());
    //不管是可见还是不可见都将光标设置到最后一个文字的后面
    Selection.setSelection((Spannable)t,t.length());

      好啦,思路讲完啦,接下来我会附上所有的代码

    布局文件的代码

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#95CAE4"
        >
        <com.example.clearedittext.ClearEditText
            android:id="@+id/username"
            android:layout_marginTop="60dp"
            android:layout_width="fill_parent"
            android:background="@drawable/login_edittext_bg" 
            android:drawableLeft="@drawable/icon_user"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:singleLine="true"
            android:drawableRight="@drawable/delete_selector"
            android:hint="输入用户名"
            android:layout_height="wrap_content" >
    
        </com.example.clearedittext.ClearEditText>
    
        <com.example.clearedittext.ClearEditText
            android:id="@+id/password"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip"
            android:layout_marginTop="10dip"
            android:drawableLeft="@drawable/account_icon"
            android:hint="输入密码"
            android:singleLine="true"
            android:inputType="textPassword"
            android:drawableRight="@drawable/delete_selector"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/username"
            android:background="@drawable/login_edittext_bg" >
        </com.example.clearedittext.ClearEditText>
    
        <Button
            android:id="@+id/login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/password"
            android:layout_marginRight="10dip"
            android:layout_marginTop="25dp"
            android:layout_toRightOf="@+id/cb"
            android:background="@drawable/login_button_bg"
            android:text="登录"
            android:textColor="@android:color/white"
            android:textSize="18sp" />
    
        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/login"
            android:layout_alignBottom="@+id/login"
            android:layout_alignParentLeft="true"
            android:text="显示密码" />
    
    </RelativeLayout>
    View Code

    自定义EditText代码

    package com.example.clearedittext;
    
    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.text.Editable;
    import android.text.InputType;
    import android.text.Selection;
    import android.text.Spannable;
    import android.text.TextWatcher;
    import android.text.method.HideReturnsTransformationMethod;
    import android.text.method.PasswordTransformationMethod;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnFocusChangeListener;
    import android.view.animation.Animation;
    import android.view.animation.CycleInterpolator;
    import android.view.animation.TranslateAnimation;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class ClearEditText extends EditText implements  
            OnFocusChangeListener, TextWatcher { 
        /**
         * 删除按钮的引用
         */
        private Drawable mClearDrawable; 
        /**
         * 控件是否有焦点
         */
        private boolean hasFoucs;
        
        private boolean isShow = false;
     
        public ClearEditText(Context context) { 
            this(context, null); 
        } 
     
        public ClearEditText(Context context, AttributeSet attrs) { 
            //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
            this(context, attrs, android.R.attr.editTextStyle); 
        } 
        
        public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
        
        
        private void init() { 
            //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,getCompoundDrawables()获取Drawable的四个位置的数组
            mClearDrawable = getCompoundDrawables()[2]; 
            if (mClearDrawable == null) {
                mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
    //            throw new NullPointerException("You can add drawableRight attribute in XML");
            } 
            //设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
            mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); 
            //默认设置隐藏图标
            setClearIconVisible(false); 
            //设置焦点改变的监听
            setOnFocusChangeListener(this); 
            //设置输入框里面内容发生改变的监听
            addTextChangedListener(this); 
        } 
     
     
        /**
         * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
         * 当我们按下的位置 在  EditText的宽度 - 图标到控件右边的间距 - 图标的宽度  和
         * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
         */
        @Override 
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (getCompoundDrawables()[2] != null) {
                    //getTotalPaddingRight()图标左边缘至控件右边缘的距离
                    //getWidth() - getTotalPaddingRight()表示从最左边到图标左边缘的位置
                    //getWidth() - getPaddingRight()表示最左边到图标右边缘的位置
                    boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                            && (event.getX() < ((getWidth() - getPaddingRight())));
                    
                    if (touchable) {
                        this.setText("");
                    }
                }
    //            if(getCompoundDrawables()[0] != null){
    //                boolean touchLeft = event.getX()>0 && event.getX()<getCompoundDrawables()[0].getIntrinsicWidth();
    //                if(touchLeft){
    //                    if(isShow==false){
    //                        isShow = true;
    //                        //设置为可见
    //                        this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    //                    }else{
    //                        isShow = false;
    //                        //设置为密码模式
    //                        this.setTransformationMethod(PasswordTransformationMethod.getInstance());
    //                    }
    //                }
    //            }
            }
    
            return super.onTouchEvent(event);
        }
        /**
         * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
         */
        @Override 
        public void onFocusChange(View v, boolean hasFocus) { 
            this.hasFoucs = hasFocus;
            if (hasFocus) { 
                setClearIconVisible(getText().length() > 0); 
            } else { 
                setClearIconVisible(false); 
            } 
        } 
        /**
         * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
         * @param visible
         */
        protected void setClearIconVisible(boolean visible) { 
            Drawable right = visible ? mClearDrawable : null; 
            setCompoundDrawables(getCompoundDrawables()[0], 
                    getCompoundDrawables()[1], right, getCompoundDrawables()[3]); 
        }
        /**
         * 当输入框里面内容发生变化的时候回调的方法
         */
        @Override 
        public void onTextChanged(CharSequence s, int start, int count, 
                int after) { 
                    if(hasFoucs){
                        setClearIconVisible(s.length() > 0);
                    }
        } 
     
        @Override 
        public void beforeTextChanged(CharSequence s, int start, int count, 
                int after) { 
             
        } 
     
        @Override 
        public void afterTextChanged(Editable s) { 
             
        } 
        /**
         * 设置晃动动画
         */
        public void setShakeAnimation(){
            this.startAnimation(shakeAnimation(5));
        }
        
        
        /**
         * 晃动动画
         * @param counts 1秒钟晃动多少下
         * @return
         */
        public static Animation shakeAnimation(int counts){
            Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
            translateAnimation.setInterpolator(new CycleInterpolator(counts));
            translateAnimation.setDuration(1000);
            return translateAnimation;
        }
     
     
    }
    View Code

    主Activity代码也就是调用代码

    package com.example.clearedittext;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.InputType;
    import android.text.Selection;
    import android.text.Spannable;
    import android.text.TextUtils;
    import android.text.method.HideReturnsTransformationMethod;
    import android.text.method.PasswordTransformationMethod;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
        private Toast mToast;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            final ClearEditText username = (ClearEditText) findViewById(R.id.username);
            final ClearEditText password = (ClearEditText) findViewById(R.id.password);
            final CheckBox cb = (CheckBox) findViewById(R.id.cb);
            
            ((Button) findViewById(R.id.login)).setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    if(TextUtils.isEmpty(username.getText())){
                        //设置提示
                        username.setShakeAnimation();
                        showToast("用户名不能为空");
                        return;
                    }
                    
                    if(TextUtils.isEmpty(password.getText())){
                        password.setShakeAnimation();
                        showToast("密码不能为空");
                        return;
                    }
                }
            });
            
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                
                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                    if(arg1){
                        //密码设置为可见
                        password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    }else{
                        //密码设置为不可见
                        password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                    CharSequence t = password.getText();
                    
                    //不管是可见还是不可见都将光标设置到最后一个文字的后面
                    Selection.setSelection((Spannable)t,t.length());
                    
                    
                }
            });
        }
        /**
         * 显示Toast消息
         * @param msg
         */
        private void showToast(String msg){
            if(mToast == null){
                mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            }else{
                mToast.setText(msg);
            }
            mToast.show();
        }
    }
    View Code

    至于里面的图片啊什么大家就去网上找找吧

    至此Android自定义控件实现带有清除按钮的EditText就写完啦,如果发现什么漏洞,欢迎大家指出

  • 相关阅读:
    Nginx,uWSGI与Django 应用的关系
    闭包学习-Python 篇
    Django学习之REST framework JWT Auth
    Python标准库uuid模块
    Django REST framework学习之JWT失效方式
    Django学习之JWT
    单点登录
    print输出格式总结
    百钱百鸡问题
    流程图符号及其功能
  • 原文地址:https://www.cnblogs.com/luhan/p/5956708.html
Copyright © 2011-2022 走看看