Android 带清除功能的输入框控件EditText

弱龄寄事外,委怀在琴书。这篇文章主要讲述Android 带清除功能的输入框控件EditText相关的知识,希望能为你提供帮助。
今天学习了自定义控件,然后自己做了一个用户登录小控件EditText,就是在android系统的输入框右边加入一个小图标,点击小图标可以清除输入框里面的内容,但是Android原生EditText不具备此功能,所以要想实现这一功能我们需要重写EditText。
先说明一下,我是用Android studio写的,代码已经共享到我的github上了,有需要的可以去下载。
我们可以为我们的输入框在上下左右设置图片,所以我们可以利用属性android:drawableRight设置我们的删除小图标,如图

Android 带清除功能的输入框控件EditText

文章图片

这里设置了左边和右边的图片,如果我们能为右边的图片设置监听,点击右边的图片清除输入框的内容并隐藏删除图标,这样子这个小功能就迎刃而解了,可是 Android并没有给允许我们给右边小图标加监听的功能,这时候你是不是发现这条路走不通呢,其实不是,我们可能模拟点击事件,用输入框的的 onTouchEvent()方法来模拟,
当我们触摸抬起(就是ACTION_UP的时候)的范围  水平方向大于输入框左侧到清除图标左侧的距离,小与输入框左侧到清除图片右侧的距离,在竖直方向大于输入框上顶部到清除图标上侧的距离,小于输入框下底部到清除图标的距离,我们则认为是点击清除图片,只要给清除小图标就上了监听,同时也给输入框设置了晃动效果,当没有输入账户时,点击登录,就会实现输入框的晃动。下面贴一下代码。(代码中有很详细的注释)
 
package com.tony.clearedittext; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.CycleInterpolator; import android.view.animation.TranslateAnimation; import android.widget.EditText; import java.util.jar.Attributes; /** * Created by Cheng Bao on 2015/6/17. */ public class ClearEditText extends EditText implements View.OnFocusChangeListener,TextWatcher { /** * 删除按钮的引用 */ private Drawable mClearDrawable; private Context context; /** * 控件是否有焦点 */ private boolean hasFocus; public ClearEditText(Context context) { this(context,null); //super(context); //this.context = context; //init(); } 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,假如没有设置我们就使用默认的图片 mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { mClearDrawable = getResources().getDrawable(R.drawable.delete_selector); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); //默认设置隐藏图标 setClearIconVisible(false); //设置焦点改变的监听 setOnFocusChangeListener(this); //设置输入框里面内容发生改变的监听 addTextChangedListener(this); }@Override public boolean onTouchEvent(MotionEvent event) {if (mClearDrawable != null & & event.getAction() == MotionEvent.ACTION_UP) { int x = (int) event.getX(); //判断触摸点是否在水平范围内 boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) & & (x < (getWidth() - getPaddingRight())); //获取删除图标的边界,返回一个Rect对象 Rect rect = mClearDrawable.getBounds(); //获取删除图标的高度 int height = rect.height(); int y = (int) event.getY(); //计算图标底部到控件底部的距离 int distance = (getHeight() - height) / 2; //判断触摸点是否在竖直范围内(可能会有点误差) //触摸点的纵坐标在distance到(distance+图标自身的高度)之内,则视为点中删除图标 boolean isInnerHeight = (y > distance) & & (y < (distance + height)); if (isInnerHeight & & isInnerWidth) { this.setText(""); } } return super.onTouchEvent(event); }/** * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去 * * @param visible */ private void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); }/** * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFocus = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } }/** * 当输入框里面内容发生变化的时候回调的方法 */ @Override public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { if (hasFocus) { setClearIconVisible(text.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; } }

  • setClearIconVisible() 方法,设置隐藏和显示清除图标的方法,这里不是调用setVisibility()方法,setVisibility()这个方法是针对View的, 我们可以调用setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)来设置上下左右的图标
  • setOnFocusChangeListener(this)  为输入框设置焦点改变监听,如果输入框有焦点,我们判断输入框的值是否为空,为空就隐藏清除图标,否则就显示
  • addTextChangedListener(this)  为 输入框设置内容改变监听,其实很简单呢,当输入框里面的内容发生改变的时候,我们需要处理显示和隐藏清除小图标,里面的内容长度不为0我们就显示,否是就 隐藏,但这个需要输入框有焦点我们才改变显示或者隐藏,为什么要需要焦点,比如我们一个登陆界面,我们保存了用户名和密码,在登陆界面 onCreate()的时候,我们把我们保存的密码显示在用户名输入框和密码输入框里面,输入框里面内容发生改变,导致用户名输入框和密码输入框里面的清 除小图标都显示了,这显然不是我们想要的效果,所以加了一个是否有焦点的判断
  • setShakeAnimation(),这个方法是输入框左右抖动的方法,当用户名错误,输入框就在哪里抖动,其实主要是用到一个移动动画,然后设置动画的变化率为正弦曲线
接下来我们来使用它,Activity的布局,两个我们自定义的输入框,一个按钮
< 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:background="#95CAE4" tools:context=".MainActivity"> < com.tony.clearedittext.ClearEditText android:id="@+id/username" android:layout_marginTop="60dp" 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_width="match_parent" android:layout_height="wrap_content" /> < com.tony.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:password="true" android:drawableRight="@drawable/delete_selector" android:layout_below="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/login_edittext_bg" /> < Button android:id="@+id/login" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:background="@drawable/login_button_bg" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textColor="@android:color/white" android:layout_below="@+id/password" android:layout_marginTop="25dp" android:text="登录" /> < /RelativeLayout>

然后就是界面代码的编写,主要是测试输入框左右晃动
package com.tony.clearedittext; import android.app.Activity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity {private Toast mToast; private Button mButton; @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); mButton = (Button) findViewById(R.id.login); mButton.setOnClickListener(new View.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; } } }); } /** * 显示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(); } }

【Android 带清除功能的输入框控件EditText】效果图如下:
Android 带清除功能的输入框控件EditText

文章图片

项目源码下载地址:https://github.com/tonycheng93/Android-CustomLoginDemo

    推荐阅读