全面解析Android中对EditText输入实现监听的方法

全面解析Android中对EditText输入实现监听的方法,第1张

概述在Androiddesignsupport包中提供了一种在输入不合适字符时一直显示的提示方式来显示,现在已经开始在更多的应用上被使用了;这些Androidapp在显示他们的错误提示时采用的不同的方式常常让人感觉非常的不和谐。

在 AndroID design support 包中提供了一种在输入不合适字符时一直显示的提示方式来显示,现在已经开始在更多的应用上被使用了;这些 AndroID app 在显示他们的错误提示时采用的不同的方式常常让人感觉非常的不和谐。
即这个一直显示的错误消息是在 TextinputLayout 中的 EditText 周围的。这也是,作为一个奖励,提供了材料设计风格中,活泼的浮动标签在一个 APP 的用户体验中常常是最无聊的部分。
这里来讨论如何在你的输入表单上去创建一个通用的、可重用的组件来实现所有的字段验证。因为你想要在用户改正了错误的输入时就去隐藏错误提示。我们可以通过使用 TextWatchers 来实现验证。

不幸的是,在最新的support library (23.1)中,一旦你隐藏了错误提示,让它们再显示的时候,会有一个 BUG。所以这个例子是建立在这个 23.0.1 support library 上的。此时我对这个 support library 是又爱又恨的关系――每次一个新版本发布的时候我就像一个小孩在过圣诞节:我冲下楼去看圣诞老人送来的新玩具是什么,但是发现他带来新玩具的时候,我的新玩具火车缺少一些零件,他还弄坏了一些我最喜欢的玩具,还把烟囱里的烟灰踩到了地摊上。

创建我们通用的类
把我的小埋怨放到一边,让我们创建一个实现了 TextWatcher 的接口的抽象的 ErrorTextWatcher 类。对于这个简单的例子,我想说我们的 TextWatcher 总是带有 TextinputLayout,而且它可以显示一个简单的错误消息。你的用户体验设计团队可能想要显示不同的错误――如:“密码不能为空”,“密码必须包含至少一个数字”,“请输入至少 4 个字符”等。―― 但为了简单起见,每个 TextWatcher 我将只展示如何实现一个简单的消息。

public abstract class ErrorTextWatcher implements TextWatcher {  private TextinputLayout mTextinputLayout;  private String errorMessage;  protected ErrorTextWatcher(@NonNull final TextinputLayout textinputLayout,@NonNull final String errorMessage) {    this.mTextinputLayout = textinputLayout;    this.errorMessage = errorMessage;  }

我还给这个抽象类增加了一些通用的方法:

public final boolean hasError() {  return mTextinputLayout.getError() != null;}protected String getEditTextValue() {  return mTextinputLayout.getEditText().getText().toString();}

我也想要我所有的 ErrorTextWatchers 都实现 valIDate() 方法,如果如果输入是正确的就返回 true,这样能简单的去显示或隐藏错误:

public abstract boolean valIDate();protected voID showError(final boolean error) {  if (!error) {    mTextinputLayout.setError(null);    mTextinputLayout.setErrorEnabled(false);  } else {    if (!errorMessage.equals(mTextinputLayout.getError())) {      // Stop the flickering that happens when setting the same error message multiple times      mTextinputLayout.setError(errorMessage);    }    mTextinputLayout.requestFocus();  }}

在我的代码上,这个库在这里有另外一个功能:在我看来通过设置错误提示的 enabled 为 false,你就应该能隐藏错误提示,但是这会让 EditText 的下划线仍然显示不正确的颜色,所以你既需要设置错误提示为空,也需要让下划线的颜色恢复。同样,如果你不断地设置相同的错误字符串,这个错误提示会随着动画不断的闪烁,所以只有当错误提示有新的值时才要去重写。

最后,当焦点在 TextWatcher 内的 EditText 上时,我有一点点调皮的要求 ――当你看到我是如何验证输入表单的,希望你能明白我为什么这么做,但是对于你的需求,你可能想要把这段逻辑移到其他地方。

作为一个额外的优化,我发现我可以在 onTextChanged 方法的 TextWatcher 接口内实现我所有的逻辑,所以我给 beforeTextChanged 和 afterTextChanged 的父类增加了两个空方法。

最小长度验证
现在,让我们这个类的一个具体的例子。一个常见的用例是输入字段需要至少为 x 个的字符。因此,让我们创建一个 MinimumLengthTextWatcher。它带有一个最小长度值,当然,在父类中,我还需要 TextinputLayout 和 message。此外,我不想在他们输入完成之前一直告诉用户他们需要输入 x 个字符――这会是一个坏的用户体验――所以我们应该在用户已经超出了最小限制字符的时候来开始显示错误。(译者注:可以理解为当用户输入的长度超过最小限制字符之后,用户再删除一部分字符,如果此时少于最小限制字符,就会显示错误了,这样就能理解了)

public class MinimumLengthTextWatcher extends ErrorTextWatcher {  private final int mMinLength;  private boolean mReachedMinLength = false;  public MinimumLengthTextWatcher(final TextinputLayout textinputLayout,final int minLength) {    this(textinputLayout,minLength,R.string.error_too_few_characters);  }  public MinimumLengthTextWatcher(final TextinputLayout textinputLayout,final int minLength,@StringRes final int errorMessage) {    super(textinputLayout,String.format(textinputLayout.getContext().getString(errorMessage),minLength));    this.mMinLength = minLength;  }

这里有两个构造方法:一个是具有默认的消息,还有一个是对于特殊的文本字段你可以创建一个更具体的值。因为我们想要支持当地化,我们采用 AndroID string 资源文件,而不是硬编码 String 的值。

我们文本的改变和验证方法现在已经像下面这样简单的实现了:

@OverrIDepublic voID onTextChanged(final CharSequence text…) {  if (mReachedMinLength) {    valIDate();  }  if (text.length() >= mMinLength) {    mReachedMinLength = true;  }}@OverrIDepublic boolean valIDate() {  mReachedMinLength = true; // This may not be true but Now we want to force the error to be shown  showError(getEditTextValue().length() < mMinLength);  return !hasError();}

你会注意到,一旦验证方法在 TextWatcher 中被调起的话,它将会显示错误。我想这适用于大多数情况,但是你可能想要引入一个 setter 方法去重置某些情况下的这种行为。

你现在需要去给你的 TextinputLayout 增加 TextWatcher,接着在你的 Activity 或 Fragment 中去创建 vIEws。就像这样:

mPasswordVIEw = (TextinputLayout) findVIEwByID(R.ID.password_text_input_layout);mValIDPasswordTextWatcher = new MinimumLengthTextWatcher(mPasswordVIEw,getResources().getInteger(R.integer.min_length_password));mPasswordVIEw.getEditText().addTextChangedListener(mValIDPasswordTextWatcher);

然后,在你代码的合适位置,你可以检查一个字段是否有效:

boolean isValID = mValIDPasswordTextWatcher.valIDate();
如果密码是无效的,这个 VIEw 会自动的获得焦点并将屏幕滚动到这里。

验证电子邮件地址
另一种常见的验证用例是检查电子邮件地址是否是有效的。我可以很容易的写一整篇都关于用正则表达式来验证邮件地址的文章,但是因为这常常是有争议的,我已经从 TextWatcher 本身分开了邮件验证的逻辑。示例项目包含了可测试的 EmailAddressValIDator,你可以用它,或者你也可以用你自己想要的逻辑来实现。

既然我已经把邮件验证逻辑分离出来了,ValIDEmailTextWatcher 是和 MinimumLengthTextWatcher 非常相似的。

public class ValIDEmailTextWatcher extends ErrorTextWatcher {  private final EmailAddressValIDator mValIDator = new EmailAddressValIDator();  private boolean mValIDated = false;  public ValIDEmailTextWatcher(@NonNull final TextinputLayout textinputLayout) {    this(textinputLayout,R.string.error_invalID_email);  }  public ValIDEmailTextWatcher(@NonNull final TextinputLayout textinputLayout,textinputLayout.getContext().getString(errorMessage));  }  @OverrIDe  public voID onTextChanged(…) {    if (mValIDated) {      valIDate();    }  }  @OverrIDe  public boolean valIDate() {    showError(!mValIDator.isValID(getEditTextValue()));    mValIDated = true;    return !hasError();  }

这个 TextWatcher 在我们的 Activity 或 Fragment 内的实现方式是和之前的是非常像的:

mEmailVIEw = (TextinputLayout) findVIEwByID(R.ID.email_text_input_layout);mValIDEmailTextWatcher = new ValIDEmailTextWatcher(mEmailVIEw);mEmailVIEw.getEditText().addTextChangedListener(mValIDEmailTextWatcher);

把它放在一起
对于表单注册或登录,在提交给你的 API 之前,你通常会验证所有的字段。因为我们要求关注在 TextWatcher 的任何 vIEws 的失败验证。我一般在从下往上验证所有的 vIEw。这样,应用程序显示所有需要纠正字段的错误,然后跳转到表单上第一个错误输入的文本。例如:

private boolean allFIEldsAreValID() {  /**   * Since the text watchers automatically focus on erroneous fIElds,do them in reverse order so that the first one in the form gets focus   * &= may not be the easIEst construct to decipher but it's a lot more concise. It just means that once it's false it doesn't get set to true   */  boolean isValID = mValIDPasswordTextWatcher.valIDate();  isValID &= mValIDEmailTextWatcher.valIDate();  return isValID;}

你可以找到上述所有代码的例子在 GitHub[1] 上。这是一个在 ClearableEditText 上的分支,我是基于 让你的 EditText 全部清除[2] 这篇博客上的代码来进行阐述的,但是把它用在标准的 EditText 上也是一样的。它还包括了一些更多的技巧和 BUG 处理,我没有时间在这里提了。

尽管我只显示了两个 TextWatcher 的例子,但我希望你能看到这是多么简单,你现在能添加其他的 TextWatcher 去给任何文本输入添加不同的验证方法,并在你的 APP 中去请求验证和重用。

带清除功能的输入框控件ClearEditText
下面给大家带来一个很实用的小控件ClearEditText,就是在AndroID系统的输入框右边加入一个小图标,点击小图标可以清除输入框里面的内容,IOS上面直接设置某个属性就可以实现这一功能,但是AndroID原生EditText不具备此功能,所以要想实现这一功能我们需要重写EditText,接下来就带大家来实现这一小小的功能
我们知道,我们可以为我们的输入框在上下左右设置图片,所以我们可以利用属性androID:drawableRight设置我们的删除小图标,如图

我这里设置了左边和右边的图片,如果我们能为右边的图片设置监听,点击右边的图片清除输入框的内容并隐藏删除图标,这样子这个小功能就迎刃而解了,可是AndroID并没有给允许我们给右边小图标加监听的功能,这时候你是不是发现这条路走不通呢,其实不是,我们可能模拟点击事件,用输入框的的ontouchEvent()方法来模拟,
当我们触摸抬起(就是ACTION_UP的时候)的范围  大于输入框左侧到清除图标左侧的距离,小与输入框左侧到清除图片右侧的距离,我们则认为是点击清除图片,当然我这里没有考虑竖直方向,只要给清除小图标就上了监听,其他的就都好处理了,我先把代码贴上来,在讲解下

package com.example.clearedittext;  import androID.content.Context; 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.VIEw.OnFocuschangelistener; import androID.vIEw.animation.Animation; import androID.vIEw.animation.CycleInterpolator; import androID.vIEw.animation.TranslateAnimation; import androID.Widget.EditText;  public class ClearEditText extends EditText implements      OnFocuschangelistener,TextWatcher {    /**    * 删除按钮的引用    */   private Drawable mClearDrawable;    /**    * 控件是否有焦点    */   private boolean hasFoucs;     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,defStyle);     init();   }         private voID init() {      //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片     mClearDrawable = getCompoundDrawables()[2];      if (mClearDrawable == null) {  //     throw new NullPointerException("You can add drawableRight attribute in XML");       mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);      }           mClearDrawable.setBounds(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) {          boolean touchable = event.getX() > (getWIDth() - getTotalpaddingRight())             && (event.getX() < ((getWIDth() - getpaddingRight())));                  if (touchable) {           this.setText("");         }       }     }      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 after) {          }      @OverrIDe    public voID afterTextChanged(Editable s) {          }          /**    * 设置晃动动画    */   public voID setShakeAnimation(){     this.setAnimation(shakeAnimation(5));   }         /**    * 晃动动画    * @param counts 1秒钟晃动多少下    * @return    */   public static Animation shakeAnimation(int counts){     Animation translateAnimation = new TranslateAnimation(0,10,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: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:password="true"     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_marginleft="10dip"     androID:layout_marginRight="10dip"     androID:background="@drawable/login_button_bg"     androID:textSize="18sp"     androID:textcolor="@androID:color/white"     androID:layout_below="@+ID/password"     androID:layout_margintop="25dp"     androID:text="登录" />  </relativeLayout> 

然后就是界面代码的编写,主要是测试输入框左右晃动而已,比较简单

package com.example.clearedittext;  import androID.app.Activity; import androID.os.Bundle; import androID.text.TextUtils; import androID.vIEw.VIEw; import androID.vIEw.VIEw.OnClickListener; import androID.Widget.button; 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);          ((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;         }       }     });   }      /**    * 显示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输入实现监听的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1149480.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存