首页 > 代码库 > 自定义的Android EditText

自定义的Android EditText

这是一个指定EditText,在我们的实际开发中,可以直接拿来用就行了,先上图看效果:

      

简单介绍下:当文本框有字符串时,在右边会显示一个清除的图标。点击清除的图标可以清除文本框的内容。

 

先上自定义编辑框代码:代码比较简单,值得注意的是onTouchEvent方法。这个是一个触摸事件,主要捕获清除图标,模拟点击事件。

  1 package cn.datian.customedit;  2   3 import android.content.Context;  4 import android.graphics.drawable.Drawable;  5 import android.text.Editable;  6 import android.text.TextWatcher;  7 import android.util.AttributeSet;  8 import android.view.MotionEvent;  9 import android.view.View; 10 import android.view.View.OnFocusChangeListener; 11 import android.view.animation.Animation; 12 import android.view.animation.CycleInterpolator; 13 import android.view.animation.TranslateAnimation; 14 import android.widget.EditText; 15  16 public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { 17     /** 18      * 删除按钮的引用 19      */ 20     private Drawable mClearDrawable; 21  22     /** 23      * 控件是否有焦点 24      */ 25     private boolean hasFoucs; 26  27     public ClearEditText(Context context) { 28         this(context, null); 29     } 30  31     public ClearEditText(Context context, AttributeSet attrs) { 32         // 这里构造方法也很重要,不加这个很多属性不能再XML里面定义 33         this(context, attrs, android.R.attr.editTextStyle); 34     } 35  36     public ClearEditText(Context context, AttributeSet attrs, int defStyle) { 37         super(context, attrs, defStyle); 38         init(); 39     } 40  41     private void init() { 42         // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片 43         mClearDrawable = getCompoundDrawables()[2]; 44         if (mClearDrawable == null) { 45             mClearDrawable = getResources().getDrawable(R.drawable.delete_selector); 46         } 47         mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), 48                 mClearDrawable.getIntrinsicHeight()); 49         // 默认设置隐藏图标 50         setClearIconVisible(false); 51         // 设置焦点改变的监听 52         setOnFocusChangeListener(this); 53         // 设置输入框里面内容发生改变的监听 54         addTextChangedListener(this); 55     } 56  57     /** 58      * 触摸事件,此方法的目的是给清除图标一个触摸事件(模拟点击事件),当触摸到清除图片的位置时,清除编辑框里面的内容 59      * 捕获清除图标位置的代码:event.getX() > (getWidth() - getTotalPaddingRight()) 60      *                   && (event.getX() < ((getWidth() - getPaddingRight()))) 61      * 返回true表示触摸到清除图标,清除编辑框里面的内容,返回false则不处理。 62      */ 63     @Override 64     public boolean onTouchEvent(MotionEvent event) { 65         if (event.getAction() == MotionEvent.ACTION_UP) { 66             if (getCompoundDrawables()[2] != null) { 67  68                 boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight()) 69                         && (event.getX() < ((getWidth() - getPaddingRight()))); 70  71                 int r= getTotalPaddingRight(); 72                 int r2 = getPaddingRight(); 73                 if (touchable) { 74                     this.setText(""); 75                 } 76             } 77         } 78  79         return super.onTouchEvent(event); 80     } 81  82     /** 83      * 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 84      */ 85     @Override 86     public void onFocusChange(View v, boolean hasFocus) { 87         this.hasFoucs = hasFocus; 88         if (hasFocus) { 89             setClearIconVisible(getText().length() > 0); 90         } else { 91             setClearIconVisible(false); 92         } 93     } 94  95     /** 96      * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去 97      *  98      * @param visible 99      */100     protected void setClearIconVisible(boolean visible) {101         Drawable right = visible ? mClearDrawable : null;102         Drawable[] mDrawables = getCompoundDrawables();103         setCompoundDrawables(mDrawables[0], mDrawables[1], right,104                 mDrawables[3]);105     }106 107     /**108      * 当输入框里面内容发生变化的时候回调的方法109      */110     @Override111     public void onTextChanged(CharSequence s, int start, int count, int after) {112         if (hasFoucs) {113             setClearIconVisible(s.length() > 0);114         }115     }116 117     /**118      * 当输入框里面内容发生变化之前回调的方法119      */120     @Override121     public void beforeTextChanged(CharSequence s, int start, int count, int after) {122 123     }124 125     /**126      * 当输入框里面内容发生变化之后回调的方法127      */128     @Override129     public void afterTextChanged(Editable s) {130 131     }132 133     /**134      * 设置晃动动画135      */136     public void setShakeAnimation() {137         this.setAnimation(shakeAnimation(5,300));138     }139 140    /**141     * 晃动动画142     * @param counts  晃动次数  143     * @param duration  晃动持续时间(毫秒)144     * @return145     */146     private Animation shakeAnimation(int counts,int duration) {147         Animation translateAnimation = new TranslateAnimation(-1, 1, -1, 1);148         translateAnimation.setInterpolator(new CycleInterpolator(counts));149         translateAnimation.setDuration(duration);150         return translateAnimation;151     }152 }

 

布局XML代码:

 1 <LinearLayout 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     tools:context=".MainActivity"  6     android:orientation="vertical" 7     > 8     <cn.datian.customedit.ClearEditText 9         android:id="@+id/et"10         android:layout_width="match_parent"11         android:layout_height="wrap_content"12          android:background="@drawable/login_edittext_bg"13          android:drawableRight="@drawable/delete_selector"14          android:singleLine="true" 15         />16     <Button17         android:id="@+id/button1"18         android:layout_width="wrap_content"19         android:layout_height="wrap_content"20         android:text="Button" />21 22 </LinearLayout>

delete_selector和login_edittext_bg是选择器:代码如下

delete_selector选择器代码:

1 <?xml version="1.0" encoding="utf-8"?>2 <selector3   xmlns:android="http://schemas.android.com/apk/res/android">4     <item android:state_pressed="true" android:drawable="@drawable/search_clear_pressed" />5     <item android:drawable="@drawable/search_clear_normal" />6 </selector>

login_edittext_bg选择器代码:

1 <?xml version="1.0" encoding="UTF-8"?>2 <selector xmlns:android="http://schemas.android.com/apk/res/android">3     <item android:state_focused="true" android:drawable="@drawable/login_edit_pressed"></item>4     <item android:state_pressed="true" android:drawable="@drawable/login_edit_pressed"></item>5     <item android:drawable="@drawable/login_edit_normal"></item>6 </selector>

 

Activity代码:

 1 package cn.datian.customedit; 2  3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.View; 6 import android.widget.Button; 7 import android.widget.Toast; 8  9 public class MainActivity extends Activity {10 11     private ClearEditText et;12     @Override13     protected void onCreate(Bundle savedInstanceState) {14         super.onCreate(savedInstanceState);15         setContentView(R.layout.activity_main);16         17         Button btnLogin = (Button)this.findViewById(R.id.button1);18         et = (ClearEditText)this.findViewById(R.id.et);19         20         btnLogin.setOnClickListener(new View.OnClickListener() {21             22             @Override23             public void onClick(View v) {24                 String etStr = et.getText().toString();25                 if(etStr.equals("") || etStr==null){26                     //如果编辑框为空的话,抖动提示27                     et.setShakeAnimation();28                     Toast.makeText(MainActivity.this, "不能为空", Toast.LENGTH_SHORT).show();29                 }30             }31         });32     }33 }