首先聲明我也是參考了別人的思路,只是稍微做了下修改,增加顯示密碼與隱藏密碼,沒有輸入字符串時讓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()[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); } /** * 因為我們不能直接給EditText設置點擊事件,所以我們用記住我們按下的位置來模擬點擊事件 * 當我們按下的位置 在 EditText的寬度 - 圖標到控件右邊的間距 - 圖標的寬度 和 * EditText的寬度 - 圖標到控件右邊的間距之間我們就算點擊了圖標,豎直方向就沒有考慮 */ @Override 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); } /** * 當ClearEditText焦點發生變化的時候,判斷里面字符串長度設置清除圖標的顯示與隱藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFoucs = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } /** * 設置清除圖標的顯示與隱藏,調用setCompoundDrawables為EditText繪制上去 * @param visible */
protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } /** * 當輸入框里面內容發生變化的時候回調的方法 */ @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if(hasFoucs){ setClearIconVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } /** * 設置晃動動畫 */
public void setShakeAnimation(){ this.startAnimation(shakeAnimation(5)); } /** * 晃動動畫 * @param counts 1秒鍾晃動多少下 * @return */
public static Animation shakeAnimation(int counts){ Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); 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就寫完啦,如果發現什么漏洞,歡迎大家指出