首先声明我也是参考了别人的思路,只是稍微做了下修改,增加显示密码与隐藏密码,没有输入字符串时让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>

自定义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()[];
if (mClearDrawable == null) {
mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
// throw new NullPointerException("You can add drawableRight attribute in XML");
}
//设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
mClearDrawable.setBounds(, , 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()[] != 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() > );
} else {
setClearIconVisible(false);
}
}
/**
* 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
* @param visible
*/
protected void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[],
getCompoundDrawables()[], right, getCompoundDrawables()[]);
}
/**
* 当输入框里面内容发生变化的时候回调的方法
*/
@Override
public void onTextChanged(CharSequence s, int start, int count,
int after) {
if(hasFoucs){
setClearIconVisible(s.length() > );
}
} @Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) { } @Override
public void afterTextChanged(Editable s) { }
/**
* 设置晃动动画
*/
public void setShakeAnimation(){
this.startAnimation(shakeAnimation());
} /**
* 晃动动画
* @param counts 1秒钟晃动多少下
* @return
*/
public static Animation shakeAnimation(int counts){
Animation translateAnimation = new TranslateAnimation(, , , );
translateAnimation.setInterpolator(new CycleInterpolator(counts));
translateAnimation.setDuration();
return translateAnimation;
} }

主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();
}
}

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

至此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. laravel 操作数据库

    建立student控制器,控制器代码 namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class StudentC ...

  2. T3185 队列练习1 codevs

    http://codevs.cn/problem/3185/ 题目描述 Description 给定一个队列(初始为空),只有两种操作入队和出队,现给出这些操作请输出最终的队头元素. 操作解释:1表示 ...

  3. ios 处理内存警告

    iPhone下每个app可用的内存是被限制的,如果一个app使用的内存超过20M,则系统会向该app发送Memory Warning消息.收到此消息后,app必须正确处理,否则可能出错或者出现内存泄露 ...

  4. crontab 实际的应用

    每二天执行一次: 0 0 */2 * * command #注意分,时不能为星*,否则每分钟执行 每天零晨01,03执行: 0 01,03 * * * command 每2小时执行一次 0 */2 * ...

  5. 微软CIO如何与业务部门打交道?

    微软公司副总裁兼CIO Tony Scott是一个非常智慧的人,他拒绝和CEO讨论IT成本的问题,认为IT不应该谈论成本,而是应该谈论IT提供服务的价值.在满足业务部门需求.为业务部门提供适当的IT支 ...

  6. 揭秘jbpm流程引擎内核设计思想及构架

    揭秘jbpm流程引擎内核设计思想及构架 作者 胡长城(银狐999)   1     前言 2     阅读本篇的基础准备 2.1      概念的基础 2.2      环境的基础 3     什么是 ...

  7. maven删除不必要的依赖;优化pom依赖研究

    mvn dependency:copy-dependencies -DoutputDirectory=/home/admin/git/oceanus/test 会把所有依赖的插件版本都拷贝进去,而不是 ...

  8. android studio 使用(一)

    官方网址入门:https://developer.android.com/studio/install.html 看下Build Your first App,

  9. Android锁屏或灭屏状态下,高速按两次音量下键实现抓拍功能(1.2Framework层使用startService形式实现)

        如前一篇博文所分析.我们能够使用广播的形式在高速按下两次音量下键的时候发出广播,以方便client进行捕捉. 既然有两种方式能够实现该Issue那么哪种方式是首选呢?     我个人推荐使用启 ...

  10. SolidEdge 如何绘制辅助视图

    如果你要创建辅助视图,则点击辅助视图按钮,然后鼠标滑过要正视的面上,出现灰色的时候向上拉即可.   你可以右击箭头,点击性质,改变箭头的符号等样式.