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

效果很赞有木有

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

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

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

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

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

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

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

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

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

  1. boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
  2. && (event.getX() < ((getWidth() - getPaddingRight())));
  3.  
  4. if (touchable) {
  5. this.setText("");
  6. }可以看到如果正好是清除按钮的位置我们就调用setText方法赋值一个空字符达到清除的目的
  1. public boolean onTouchEvent(MotionEvent event) {
  2. if (event.getAction() == MotionEvent.ACTION_UP) {
  3. if (getCompoundDrawables()[2] != null) {
  4. //getTotalPaddingRight()图标左边缘至控件右边缘的距离
  5. //getWidth() - getTotalPaddingRight()表示从最左边到图标左边缘的位置
  6. //getWidth() - getPaddingRight()表示最左边到图标右边缘的位置
  7. boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
  8. && (event.getX() < ((getWidth() - getPaddingRight())));
  9.  
  10. if (touchable) {
  11. this.setText("");
  12. }
  13. }
  14. // if(getCompoundDrawables()[0] != null){
  15. // boolean touchLeft = event.getX()>0 && event.getX()<getCompoundDrawables()[0].getIntrinsicWidth();
  16. // if(touchLeft){
  17. // if(isShow==false){
  18. // isShow = true;
  19. // //设置为可见
  20. // this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
  21. // }else{
  22. // isShow = false;
  23. // //设置为密码模式
  24. // this.setTransformationMethod(PasswordTransformationMethod.getInstance());
  25. // }
  26. // }
  27. // }
  28. }
  29.  
  30. return super.onTouchEvent(event);
  31. }

  再就是EditText的晃动动画了

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

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

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

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

布局文件的代码

  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. >
  7. <com.example.clearedittext.ClearEditText
  8. android:id="@+id/username"
  9. android:layout_marginTop="60dp"
  10. android:layout_width="fill_parent"
  11. android:background="@drawable/login_edittext_bg"
  12. android:drawableLeft="@drawable/icon_user"
  13. android:layout_marginLeft="10dip"
  14. android:layout_marginRight="10dip"
  15. android:singleLine="true"
  16. android:drawableRight="@drawable/delete_selector"
  17. android:hint="输入用户名"
  18. android:layout_height="wrap_content" >
  19.  
  20. </com.example.clearedittext.ClearEditText>
  21.  
  22. <com.example.clearedittext.ClearEditText
  23. android:id="@+id/password"
  24. android:layout_marginLeft="10dip"
  25. android:layout_marginRight="10dip"
  26. android:layout_marginTop="10dip"
  27. android:drawableLeft="@drawable/account_icon"
  28. android:hint="输入密码"
  29. android:singleLine="true"
  30. android:inputType="textPassword"
  31. android:drawableRight="@drawable/delete_selector"
  32. android:layout_width="fill_parent"
  33. android:layout_height="wrap_content"
  34. android:layout_below="@id/username"
  35. android:background="@drawable/login_edittext_bg" >
  36. </com.example.clearedittext.ClearEditText>
  37.  
  38. <Button
  39. android:id="@+id/login"
  40. android:layout_width="fill_parent"
  41. android:layout_height="wrap_content"
  42. android:layout_below="@+id/password"
  43. android:layout_marginRight="10dip"
  44. android:layout_marginTop="25dp"
  45. android:layout_toRightOf="@+id/cb"
  46. android:background="@drawable/login_button_bg"
  47. android:text="登录"
  48. android:textColor="@android:color/white"
  49. android:textSize="18sp" />
  50.  
  51. <CheckBox
  52. android:id="@+id/cb"
  53. android:layout_width="wrap_content"
  54. android:layout_height="wrap_content"
  55. android:layout_alignBaseline="@+id/login"
  56. android:layout_alignBottom="@+id/login"
  57. android:layout_alignParentLeft="true"
  58. android:text="显示密码" />
  59.  
  60. </RelativeLayout>

自定义EditText代码

  1. package com.example.clearedittext;
  2.  
  3. import android.content.Context;
  4. import android.graphics.drawable.Drawable;
  5. import android.text.Editable;
  6. import android.text.InputType;
  7. import android.text.Selection;
  8. import android.text.Spannable;
  9. import android.text.TextWatcher;
  10. import android.text.method.HideReturnsTransformationMethod;
  11. import android.text.method.PasswordTransformationMethod;
  12. import android.util.AttributeSet;
  13. import android.view.MotionEvent;
  14. import android.view.View;
  15. import android.view.View.OnFocusChangeListener;
  16. import android.view.animation.Animation;
  17. import android.view.animation.CycleInterpolator;
  18. import android.view.animation.TranslateAnimation;
  19. import android.widget.EditText;
  20. import android.widget.Toast;
  21.  
  22. public class ClearEditText extends EditText implements
  23. OnFocusChangeListener, TextWatcher {
  24. /**
  25. * 删除按钮的引用
  26. */
  27. private Drawable mClearDrawable;
  28. /**
  29. * 控件是否有焦点
  30. */
  31. private boolean hasFoucs;
  32.  
  33. private boolean isShow = false;
  34.  
  35. public ClearEditText(Context context) {
  36. this(context, null);
  37. }
  38.  
  39. public ClearEditText(Context context, AttributeSet attrs) {
  40. //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
  41. this(context, attrs, android.R.attr.editTextStyle);
  42. }
  43.  
  44. public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
  45. super(context, attrs, defStyle);
  46. init();
  47. }
  48.  
  49. private void init() {
  50. //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,getCompoundDrawables()获取Drawable的四个位置的数组
  51. mClearDrawable = getCompoundDrawables()[];
  52. if (mClearDrawable == null) {
  53. mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
  54. // throw new NullPointerException("You can add drawableRight attribute in XML");
  55. }
  56. //设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
  57. mClearDrawable.setBounds(, , mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
  58. //默认设置隐藏图标
  59. setClearIconVisible(false);
  60. //设置焦点改变的监听
  61. setOnFocusChangeListener(this);
  62. //设置输入框里面内容发生改变的监听
  63. addTextChangedListener(this);
  64. }
  65.  
  66. /**
  67. * 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
  68. * 当我们按下的位置 在 EditText的宽度 - 图标到控件右边的间距 - 图标的宽度 和
  69. * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
  70. */
  71. @Override
  72. public boolean onTouchEvent(MotionEvent event) {
  73. if (event.getAction() == MotionEvent.ACTION_UP) {
  74. if (getCompoundDrawables()[] != null) {
  75. //getTotalPaddingRight()图标左边缘至控件右边缘的距离
  76. //getWidth() - getTotalPaddingRight()表示从最左边到图标左边缘的位置
  77. //getWidth() - getPaddingRight()表示最左边到图标右边缘的位置
  78. boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
  79. && (event.getX() < ((getWidth() - getPaddingRight())));
  80.  
  81. if (touchable) {
  82. this.setText("");
  83. }
  84. }
  85. // if(getCompoundDrawables()[0] != null){
  86. // boolean touchLeft = event.getX()>0 && event.getX()<getCompoundDrawables()[0].getIntrinsicWidth();
  87. // if(touchLeft){
  88. // if(isShow==false){
  89. // isShow = true;
  90. // //设置为可见
  91. // this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
  92. // }else{
  93. // isShow = false;
  94. // //设置为密码模式
  95. // this.setTransformationMethod(PasswordTransformationMethod.getInstance());
  96. // }
  97. // }
  98. // }
  99. }
  100.  
  101. return super.onTouchEvent(event);
  102. }
  103. /**
  104. * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
  105. */
  106. @Override
  107. public void onFocusChange(View v, boolean hasFocus) {
  108. this.hasFoucs = hasFocus;
  109. if (hasFocus) {
  110. setClearIconVisible(getText().length() > );
  111. } else {
  112. setClearIconVisible(false);
  113. }
  114. }
  115. /**
  116. * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
  117. * @param visible
  118. */
  119. protected void setClearIconVisible(boolean visible) {
  120. Drawable right = visible ? mClearDrawable : null;
  121. setCompoundDrawables(getCompoundDrawables()[],
  122. getCompoundDrawables()[], right, getCompoundDrawables()[]);
  123. }
  124. /**
  125. * 当输入框里面内容发生变化的时候回调的方法
  126. */
  127. @Override
  128. public void onTextChanged(CharSequence s, int start, int count,
  129. int after) {
  130. if(hasFoucs){
  131. setClearIconVisible(s.length() > );
  132. }
  133. }
  134.  
  135. @Override
  136. public void beforeTextChanged(CharSequence s, int start, int count,
  137. int after) {
  138.  
  139. }
  140.  
  141. @Override
  142. public void afterTextChanged(Editable s) {
  143.  
  144. }
  145. /**
  146. * 设置晃动动画
  147. */
  148. public void setShakeAnimation(){
  149. this.startAnimation(shakeAnimation());
  150. }
  151.  
  152. /**
  153. * 晃动动画
  154. * @param counts 1秒钟晃动多少下
  155. * @return
  156. */
  157. public static Animation shakeAnimation(int counts){
  158. Animation translateAnimation = new TranslateAnimation(, , , );
  159. translateAnimation.setInterpolator(new CycleInterpolator(counts));
  160. translateAnimation.setDuration();
  161. return translateAnimation;
  162. }
  163.  
  164. }

主Activity代码也就是调用代码

  1. package com.example.clearedittext;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.text.InputType;
  6. import android.text.Selection;
  7. import android.text.Spannable;
  8. import android.text.TextUtils;
  9. import android.text.method.HideReturnsTransformationMethod;
  10. import android.text.method.PasswordTransformationMethod;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.widget.Button;
  14. import android.widget.CheckBox;
  15. import android.widget.CompoundButton;
  16. import android.widget.CompoundButton.OnCheckedChangeListener;
  17. import android.widget.Toast;
  18.  
  19. public class MainActivity extends Activity {
  20. private Toast mToast;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25.  
  26. final ClearEditText username = (ClearEditText) findViewById(R.id.username);
  27. final ClearEditText password = (ClearEditText) findViewById(R.id.password);
  28. final CheckBox cb = (CheckBox) findViewById(R.id.cb);
  29.  
  30. ((Button) findViewById(R.id.login)).setOnClickListener(new OnClickListener() {
  31.  
  32. @Override
  33. public void onClick(View v) {
  34. if(TextUtils.isEmpty(username.getText())){
  35. //设置提示
  36. username.setShakeAnimation();
  37. showToast("用户名不能为空");
  38. return;
  39. }
  40.  
  41. if(TextUtils.isEmpty(password.getText())){
  42. password.setShakeAnimation();
  43. showToast("密码不能为空");
  44. return;
  45. }
  46. }
  47. });
  48.  
  49. cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
  50.  
  51. @Override
  52. public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
  53. if(arg1){
  54. //密码设置为可见
  55. password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
  56. }else{
  57. //密码设置为不可见
  58. password.setTransformationMethod(PasswordTransformationMethod.getInstance());
  59. }
  60. CharSequence t = password.getText();
  61.  
  62. //不管是可见还是不可见都将光标设置到最后一个文字的后面
  63. Selection.setSelection((Spannable)t,t.length());
  64.  
  65. }
  66. });
  67. }
  68. /**
  69. * 显示Toast消息
  70. * @param msg
  71. */
  72. private void showToast(String msg){
  73. if(mToast == null){
  74. mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
  75. }else{
  76. mToast.setText(msg);
  77. }
  78. mToast.show();
  79. }
  80. }

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

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

Android自定义控件实现带有清除按钮的EditText的更多相关文章

  1. Android自定义View带有删除按钮的EditText

    转载请注明出处http://blog.csdn.net/xiaanming/article/details/11066685 今天给大家带来一个很实用的小控件ClearEditText,就是在Andr ...

  2. android 自定义控件——(五)按钮点击变色

    ----------------------------------按钮点击变色(源代码下有属性解释)------------------------------------------------- ...

  3. android自定义控件(3)-自定义当前按钮属性

    那么还是针对我们之前写的自定义控件:开关按钮为例来说,在之前的基础上,我们来看看有哪些属性是可以自定义的:按钮的背景图片,按钮的滑块图片,和按钮的状态(是开还是关),实际上都应该是可以在xml文件中直 ...

  4. Android笔记——Android自定义控件

    目录: 1.自定义控件概述 01_什么是自定义控件 Android系统中,继承Android系统自带的View或者ViewGroup控件或者系统自带的控件,并在这基础上增加或者重新组合成我们想要的效果 ...

  5. Android自定义控件之自定义组合控件

    前言: 前两篇介绍了自定义控件的基础原理Android自定义控件之基本原理(一).自定义属性Android自定义控件之自定义属性(二).今天重点介绍一下如何通过自定义组合控件来提高布局的复用,降低开发 ...

  6. Android自定义控件 开源组件SlidingMenu的项目集成

    在实际项目开发中,定制一个菜单,能让用户得到更好的用户体验,诚然菜单的样式各种各样,但是有一种菜单——滑动菜单,是被众多应用广泛使用的.关于这种滑动菜单的实现,我在前面的博文中也介绍了如何自定义去实现 ...

  7. android自定义控件---添加表情

    android自定义控件---添加表情 一.定义layout文件,图片不提供了 <?xml version="1.0" encoding="utf-8"? ...

  8. Android自定义控件 -- 带边框的TextView

    使用xml实现边框 原来使用带边框的TextView时一般都是用XML定义来完成,在drawable目录中定义如下所示的xml文件: <?xml version="1.0" ...

  9. Android自定义控件之自定义组合控件(三)

    前言: 前两篇介绍了自定义控件的基础原理Android自定义控件之基本原理(一).自定义属性Android自定义控件之自定义属性(二).今天重点介绍一下如何通过自定义组合控件来提高布局的复用,降低开发 ...

随机推荐

  1. 标准C程序设计七---24

    Linux应用             编程深入            语言编程 标准C程序设计七---经典C11程序设计    以下内容为阅读:    <标准C程序设计>(第7版) 作者 ...

  2. ftrace笔记

    mount -t debugfs nodev /sys/kernel/debug 在mount后,可以在debug目录下看到tracing目录,该目录包含了ftrace的控制与输出文件. (1) en ...

  3. 选取第K大数的快速选择算法和注意事项

    快速选择算法,是一种能在大致O(N)的时间内选取数组中第k大或者k小的算法.其基本思路与快速排序算法类似,也是分治的思想. 其实这个算法是个基础算法,但是不常用,所以今天编的时候错了POJ2388,才 ...

  4. HDU - 5572 An Easy Physics Problem (计算几何模板)

    [题目概述] On an infinite smooth table, there's a big round fixed cylinder and a little ball whose volum ...

  5. python多线程实践小结

    参考:http://www.cnblogs.com/tqsummer/archive/2011/01/25/1944771.html #!/usr/bin/env python import sys ...

  6. 航空售票系统设计分析(Markdownpad2图片服务器上传无法显示)

    一.体系结构设计 1.系统原型图 2.体系结构环境图 3.构建结构图 二.人机交互界面设计 1.用户分析结果及建议 本次分析的主要目标关注用户评论反馈,对反馈进行归纳,设计出用户喜欢的界面样式.用户的 ...

  7. Maven学习使用Nexus搭建Maven私服

    原文:http://www.cnblogs.com/quanyongan/archive/2013/04/24/3037589.html 为什么要搭建nexus私服,原因很简单,有些公司都不提供外网给 ...

  8. AtoS查看iOS Crash log中的16进制代码日志

    注意:crash_log一定要和打包时的archive对应上: 方法1)在Orgnizer里找到某一个archive,即:/Users/handywang/Library/Developer/Xcod ...

  9. 数据库系统学习(十)-嵌入式SQL语言之动态SQL

    第十讲 嵌入式SQL语言之动态SQL 静态SQL 区别变量和属性:高级语言向嵌入式SQL传递变量的方法 动态SQL 动态构造SQL语句是应用程序员必须掌握的重要手段 SQL语句的动态构造示例 根据界面 ...

  10. invlpg 指令简单介绍

    invlpg 指令简单介绍 void tlb_invalidate(pde_t *pgdir, void *va) { // Flush the entry only if we're modifyi ...