今天给大家带来一个非常有用的小控件ClearEditText,就是在Android系统的输入框右边增加一个小图标,点击小图标能够清除输入框里面的内容,IOS上面直接设置某个属性就能够实现这一功能。可是Android原生EditText不具备此功能,所以要想实现这一功能我们须要重写EditText,接下来就带大家来实现这一小小的功能

我们知道。我们能够为我们的输入框在上下左右设置图片,所以我们能够利用属性android:drawableRight设置我们的删除小图标。如图

我这里设置了左边和右边的图片,假设我们能为右边的图片设置监听,点击右边的图片清除输入框的内容并隐藏删除图标,这样子这个小功能就迎刃而解了,但是Android并没有给同意我们给右边小图标加监听的功能,这时候你是不是发现这条路走不通呢。事实上不是,我们可能模拟点击事件,用输入框的的onTouchEvent()方法来模拟。

当我们触摸抬起(就是ACTION_UP的时候)的范围  大于输入框左側到清除图标左側的距离。小与输入框左側到清除图片右側的距离,我们则觉得是点击清除图片。当然我这里没有考虑竖直方向,仅仅要给清除小图标就上了监听,其它的就都优点理了,我先把代码贴上来,在讲解下

[java] view
plain
copy

  1. package com.example.clearedittext;
  2. import android.content.Context;
  3. import android.graphics.drawable.Drawable;
  4. import android.text.Editable;
  5. import android.text.TextWatcher;
  6. import android.util.AttributeSet;
  7. import android.view.MotionEvent;
  8. import android.view.View;
  9. import android.view.View.OnFocusChangeListener;
  10. import android.view.animation.Animation;
  11. import android.view.animation.CycleInterpolator;
  12. import android.view.animation.TranslateAnimation;
  13. import android.widget.EditText;
  14. public class ClearEditText extends EditText implements
  15. OnFocusChangeListener, TextWatcher {
  16. /**
  17. * 删除button的引用
  18. */
  19. private Drawable mClearDrawable;
  20. /**
  21. * 控件是否有焦点
  22. */
  23. private boolean hasFoucs;
  24. public ClearEditText(Context context) {
  25. this(context, null);
  26. }
  27. public ClearEditText(Context context, AttributeSet attrs) {
  28. //这里构造方法也非常重要,不加这个非常多属性不能再XML里面定义
  29. this(context, attrs, android.R.attr.editTextStyle);
  30. }
  31. public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
  32. super(context, attrs, defStyle);
  33. init();
  34. }
  35. private void init() {
  36. //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
  37. mClearDrawable = getCompoundDrawables()[2];
  38. if (mClearDrawable == null) {
  39. //          throw new NullPointerException("You can add drawableRight attribute in XML");
  40. mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
  41. }
  42. mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
  43. //默认设置隐藏图标
  44. setClearIconVisible(false);
  45. //设置焦点改变的监听
  46. setOnFocusChangeListener(this);
  47. //设置输入框里面内容发生改变的监听
  48. addTextChangedListener(this);
  49. }
  50. /**
  51. * 由于我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
  52. * 当我们按下的位置 在  EditText的宽度 - 图标到控件右边的间距 - 图标的宽度  和
  53. * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
  54. */
  55. @Override
  56. public boolean onTouchEvent(MotionEvent event) {
  57. if (event.getAction() == MotionEvent.ACTION_UP) {
  58. if (getCompoundDrawables()[2] != null) {
  59. boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
  60. && (event.getX() < ((getWidth() - getPaddingRight())));
  61. if (touchable) {
  62. this.setText("");
  63. }
  64. }
  65. }
  66. return super.onTouchEvent(event);
  67. }
  68. /**
  69. * 当ClearEditText焦点发生变化的时候,推断里面字符串长度设置清除图标的显示与隐藏
  70. */
  71. @Override
  72. public void onFocusChange(View v, boolean hasFocus) {
  73. this.hasFoucs = hasFocus;
  74. if (hasFocus) {
  75. setClearIconVisible(getText().length() > 0);
  76. } else {
  77. setClearIconVisible(false);
  78. }
  79. }
  80. /**
  81. * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
  82. * @param visible
  83. */
  84. protected void setClearIconVisible(boolean visible) {
  85. Drawable right = visible ?

    mClearDrawable : null;

  86. setCompoundDrawables(getCompoundDrawables()[0],
  87. getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
  88. }
  89. /**
  90. * 当输入框里面内容发生变化的时候回调的方法
  91. */
  92. @Override
  93. public void onTextChanged(CharSequence s, int start, int count,
  94. int after) {
  95. if(hasFoucs){
  96. setClearIconVisible(s.length() > 0);
  97. }
  98. }
  99. @Override
  100. public void beforeTextChanged(CharSequence s, int start, int count,
  101. int after) {
  102. }
  103. @Override
  104. public void afterTextChanged(Editable s) {
  105. }
  106. /**
  107. * 设置晃动动画
  108. */
  109. public void setShakeAnimation(){
  110. this.setAnimation(shakeAnimation(5));
  111. }
  112. /**
  113. * 晃动动画
  114. * @param counts 1秒钟晃动多少下
  115. * @return
  116. */
  117. public static Animation shakeAnimation(int counts){
  118. Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
  119. translateAnimation.setInterpolator(new CycleInterpolator(counts));
  120. translateAnimation.setDuration(1000);
  121. return translateAnimation;
  122. }
  123. }
  • setClearIconVisible()方法,设置隐藏和显示清除图标的方法,我们这里不是调用setVisibility()方法。setVisibility()这种方法是针对View的,我们能够调用setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)来设置上下左右的图标
  • setOnFocusChangeListener(this) 为输入框设置焦点改变监听,假设输入框有焦点。我们推断输入框的值是否为空。为空就隐藏清除图标,否则就显示
  • addTextChangedListener(this) 为输入框设置内容改变监听。事实上非常easy呢,当输入框里面的内容发生改变的时候,我们须要处理显示和隐藏清除小图标。里面的内容长度不为0我们就显示,否是就隐藏,但这个须要输入框有焦点我们才改变显示或者隐藏,为什么要须要焦点,比方我们一个登陆界面,我们保存了username和password,在登陆界面onCreate()的时候。我们把我们保存的password显示在username输入框和password输入框里面。输入框里面内容发生改变。导致username输入框和password输入框里面的清除小图标都显示了,这显然不是我们想要的效果,所以加了一个是否有焦点的推断
  • setShakeAnimation(),这种方法是输入框左右抖动的方法。之前我在某个应用看到过类似的功能。当username错误,输入框就在哪里抖动,感觉挺好玩的,事实上主要是用到一个移动动画。然后设置动画的变化率为正弦曲线

接下来我们来使用它,Activity的布局,两个我们自己定义的输入框。一个button

[html] view
plain
copy

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#95CAE4">
  6. <com.example.clearedittext.ClearEditText
  7. android:id="@+id/username"
  8. android:layout_marginTop="60dp"
  9. android:layout_width="fill_parent"
  10. android:background="@drawable/login_edittext_bg"
  11. android:drawableLeft="@drawable/icon_user"
  12. android:layout_marginLeft="10dip"
  13. android:layout_marginRight="10dip"
  14. android:singleLine="true"
  15. android:drawableRight="@drawable/delete_selector"
  16. android:hint="输入username"
  17. android:layout_height="wrap_content" >
  18. </com.example.clearedittext.ClearEditText>
  19. <com.example.clearedittext.ClearEditText
  20. android:id="@+id/password"
  21. android:layout_marginLeft="10dip"
  22. android:layout_marginRight="10dip"
  23. android:layout_marginTop="10dip"
  24. android:drawableLeft="@drawable/account_icon"
  25. android:hint="输入password"
  26. android:singleLine="true"
  27. android:password="true"
  28. android:drawableRight="@drawable/delete_selector"
  29. android:layout_width="fill_parent"
  30. android:layout_height="wrap_content"
  31. android:layout_below="@id/username"
  32. android:background="@drawable/login_edittext_bg" >
  33. </com.example.clearedittext.ClearEditText>
  34. <Button
  35. android:id="@+id/login"
  36. android:layout_width="fill_parent"
  37. android:layout_height="wrap_content"
  38. android:layout_marginLeft="10dip"
  39. android:layout_marginRight="10dip"
  40. android:background="@drawable/login_button_bg"
  41. android:textSize="18sp"
  42. android:textColor="@android:color/white"
  43. android:layout_below="@+id/password"
  44. android:layout_marginTop="25dp"
  45. android:text="登录" />
  46. </RelativeLayout>

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

[java] view
plain
copy

  1. package com.example.clearedittext;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.text.TextUtils;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.Toast;
  9. public class MainActivity extends Activity {
  10. private Toast mToast;
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main);
  15. final ClearEditText username = (ClearEditText) findViewById(R.id.username);
  16. final ClearEditText password = (ClearEditText) findViewById(R.id.password);
  17. ((Button) findViewById(R.id.login)).setOnClickListener(new OnClickListener() {
  18. @Override
  19. public void onClick(View v) {
  20. if(TextUtils.isEmpty(username.getText())){
  21. //设置晃动
  22. username.setShakeAnimation();
  23. //设置提示
  24. showToast("username不能为空");
  25. return;
  26. }
  27. if(TextUtils.isEmpty(password.getText())){
  28. password.setShakeAnimation();
  29. showToast("password不能为空");
  30. return;
  31. }
  32. }
  33. });
  34. }
  35. /**
  36. * 显示Toast消息
  37. * @param msg
  38. */
  39. private void showToast(String msg){
  40. if(mToast == null){
  41. mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
  42. }else{
  43. mToast.setText(msg);
  44. }
  45. mToast.show();
  46. }
  47. }

执行项目。如图,悲剧,没有动画效果。算了就这样子吧,你是不是也想把它加到你的项目其中去呢,赶紧吧!

版权声明:本文博主原创文章。博客,未经同意不得转载。

Android 随着输入框控件的清除功能ClearEditText,抄IOS输入框的更多相关文章

  1. (转载) Android 带清除功能的输入框控件ClearEditText,仿IOS的输入框

    Android 带清除功能的输入框控件ClearEditText,仿IOS的输入框 标签: Android清除功能EditText仿IOS的输入框 2013-09-04 17:33 70865人阅读  ...

  2. Android自己定义控件系列案例【五】

    案例效果: 案例分析: 在开发银行相关client的时候或者开发在线支付相关client的时候常常要求用户绑定银行卡,当中银行卡号一般须要空格分隔显示.最常见的就是每4位数以空格进行分隔.以方便用户实 ...

  3. Android 中常见控件的介绍和使用

    1 TextView文本框 1.1 TextView类的结构 TextView 是用于显示字符串的组件,对于用户来说就是屏幕中一块用于显示文本的区域.TextView类的层次关系如下: java.la ...

  4. 微信小程序基础之input输入框控件

    今天主要详写一下微信小程序中的Input输入框控件,输入框在程序中是最常见的,登录,注册,获取搜索框中的内容等等都需要,同时,还需要设置不同样式的输入框,今天的代码中都要相应的使用. input输入框 ...

  5. android 自己定义控件

    Android自己定义View实现非常easy 继承View,重写构造函数.onDraw.(onMeasure)等函数. 假设自己定义的View须要有自己定义的属性.须要在values下建立attrs ...

  6. 五、Android学习第四天补充——Android的常用控件(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 五.Android学习第四天补充——Android的常用控件 熟悉常用的A ...

  7. Android其它新控件 (转)

    原文出处:http://blog.csdn.net/lavor_zl/article/details/51312715 Android其它新控件是指非Android大版本更新时提出的新控件,也非谷歌I ...

  8. 【转】Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

    Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用 分类: Android UI2015-06-15 16: ...

  9. 【风马一族_Android】第4章Android常用基本控件

    第4章Android常用基本控件 控件是Android用户界面中的一个个组成元素,在介绍它们之前,读者必须了解所有控件的父类View(视图),它好比一个盛放控件的容器. 4.1View类概述 对于一个 ...

随机推荐

  1. 欧舒丹 L'Occitane 活力清泉保湿面霜 - 男士护肤 - 香港草莓网StrawberryNET.com

    欧舒丹 L'Occitane 活力清泉保湿面霜 - 男士护肤 - 香港草莓网StrawberryNET.com 欧舒丹 活力清泉保湿面霜 50ml/1.7oz

  2. [gkk]传智-适配器设计模式,如同电源适配器

    //适配器设计模式 是图形化设计中用的.如同电源适配器 import java.awt.*; inport java.awte public calss MyFrame{ public static ...

  3. RFC2889转发性能測试用例设计和自己主动化脚本实现

    一.203_TC_FrameRate-1.tcl set chassisAddr 10.132.238.190 set islot 1 set portList {9 10} ;#端口的排列顺序是po ...

  4. MTK Android Driver:GPIO

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2JrODYxMTEw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA ...

  5. leetcode第一刷_Unique Paths

    从左上到右下,仅仅能向右或向下,问一共同拥有多少种走法. 这个问题当然能够用递归和dp来做,递归的问题是非常可能会超时,dp的问题是须要额外空间. 事实上没有其它限制条件的话,这个问题有个非常easy ...

  6. Linux 挂载NTFS文件系统

    步骤如下: 1.安装ntfs-3g包 [root@CS-1 pub]# yum install ntfs-3g 2.创建挂载目录 [root@CS-1 pub]# mkdir /data 3.挂载NT ...

  7. wpf dll和exe合并成一个新的exe

    原文:wpf dll和exe合并成一个新的exe 微软有一个工具叫ILMerge可以合并dll exe等,但是对于wpf的应用程序而言这个工具就不好用了.我的这方法也是从国外一个博客上找来的.仅供大家 ...

  8. 联系我们_鲲鹏Web数据抓取 - 专业Web数据采集服务提供者

    联系我们_鲲鹏Web数据抓取 - 专业Web数据采集服务提供者 首页 > 联系我们 我们的联系方式如下: 029 - 82542052(陕西 西安) 13389148466 或 13571845 ...

  9. leetcode 之 Permutation Sequence

    Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and ...

  10. linux yum命令

    1 安装yum install 全部安装yum install package1 安装指定的安装包package1yum groupinsall group1 安装程序组group1 2 更新和升级y ...