Android自定义控件实现带有清除按钮的EditText
首先声明我也是参考了别人的思路,只是稍微做了下修改,增加显示密码与隐藏密码,没有输入字符串时让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的更多相关文章
- Android自定义View带有删除按钮的EditText
转载请注明出处http://blog.csdn.net/xiaanming/article/details/11066685 今天给大家带来一个很实用的小控件ClearEditText,就是在Andr ...
- android 自定义控件——(五)按钮点击变色
----------------------------------按钮点击变色(源代码下有属性解释)------------------------------------------------- ...
- android自定义控件(3)-自定义当前按钮属性
那么还是针对我们之前写的自定义控件:开关按钮为例来说,在之前的基础上,我们来看看有哪些属性是可以自定义的:按钮的背景图片,按钮的滑块图片,和按钮的状态(是开还是关),实际上都应该是可以在xml文件中直 ...
- Android笔记——Android自定义控件
目录: 1.自定义控件概述 01_什么是自定义控件 Android系统中,继承Android系统自带的View或者ViewGroup控件或者系统自带的控件,并在这基础上增加或者重新组合成我们想要的效果 ...
- Android自定义控件之自定义组合控件
前言: 前两篇介绍了自定义控件的基础原理Android自定义控件之基本原理(一).自定义属性Android自定义控件之自定义属性(二).今天重点介绍一下如何通过自定义组合控件来提高布局的复用,降低开发 ...
- Android自定义控件 开源组件SlidingMenu的项目集成
在实际项目开发中,定制一个菜单,能让用户得到更好的用户体验,诚然菜单的样式各种各样,但是有一种菜单——滑动菜单,是被众多应用广泛使用的.关于这种滑动菜单的实现,我在前面的博文中也介绍了如何自定义去实现 ...
- android自定义控件---添加表情
android自定义控件---添加表情 一.定义layout文件,图片不提供了 <?xml version="1.0" encoding="utf-8"? ...
- Android自定义控件 -- 带边框的TextView
使用xml实现边框 原来使用带边框的TextView时一般都是用XML定义来完成,在drawable目录中定义如下所示的xml文件: <?xml version="1.0" ...
- Android自定义控件之自定义组合控件(三)
前言: 前两篇介绍了自定义控件的基础原理Android自定义控件之基本原理(一).自定义属性Android自定义控件之自定义属性(二).今天重点介绍一下如何通过自定义组合控件来提高布局的复用,降低开发 ...
随机推荐
- 标准C程序设计七---24
Linux应用 编程深入 语言编程 标准C程序设计七---经典C11程序设计 以下内容为阅读: <标准C程序设计>(第7版) 作者 ...
- ftrace笔记
mount -t debugfs nodev /sys/kernel/debug 在mount后,可以在debug目录下看到tracing目录,该目录包含了ftrace的控制与输出文件. (1) en ...
- 选取第K大数的快速选择算法和注意事项
快速选择算法,是一种能在大致O(N)的时间内选取数组中第k大或者k小的算法.其基本思路与快速排序算法类似,也是分治的思想. 其实这个算法是个基础算法,但是不常用,所以今天编的时候错了POJ2388,才 ...
- HDU - 5572 An Easy Physics Problem (计算几何模板)
[题目概述] On an infinite smooth table, there's a big round fixed cylinder and a little ball whose volum ...
- python多线程实践小结
参考:http://www.cnblogs.com/tqsummer/archive/2011/01/25/1944771.html #!/usr/bin/env python import sys ...
- 航空售票系统设计分析(Markdownpad2图片服务器上传无法显示)
一.体系结构设计 1.系统原型图 2.体系结构环境图 3.构建结构图 二.人机交互界面设计 1.用户分析结果及建议 本次分析的主要目标关注用户评论反馈,对反馈进行归纳,设计出用户喜欢的界面样式.用户的 ...
- Maven学习使用Nexus搭建Maven私服
原文:http://www.cnblogs.com/quanyongan/archive/2013/04/24/3037589.html 为什么要搭建nexus私服,原因很简单,有些公司都不提供外网给 ...
- AtoS查看iOS Crash log中的16进制代码日志
注意:crash_log一定要和打包时的archive对应上: 方法1)在Orgnizer里找到某一个archive,即:/Users/handywang/Library/Developer/Xcod ...
- 数据库系统学习(十)-嵌入式SQL语言之动态SQL
第十讲 嵌入式SQL语言之动态SQL 静态SQL 区别变量和属性:高级语言向嵌入式SQL传递变量的方法 动态SQL 动态构造SQL语句是应用程序员必须掌握的重要手段 SQL语句的动态构造示例 根据界面 ...
- invlpg 指令简单介绍
invlpg 指令简单介绍 void tlb_invalidate(pde_t *pgdir, void *va) { // Flush the entry only if we're modifyi ...