1. 程式人生 > >Android中ClearEditText實現點選EditText輸入框右邊清除圖示來清除輸入內容的兩種方式

Android中ClearEditText實現點選EditText輸入框右邊清除圖示來清除輸入內容的兩種方式

兩種EditText輸入框點選右邊清除圖示來實現清除功能的方式。

效果圖下圖:


佈局程式碼如下,

<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:layout_gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >
    
    <!-- 使用原始EditText實現清除輸入的功能 -->
    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="50dp"
         android:background="@drawable/btn_big_normal"
         android:gravity="center_vertical" >
        <EditText
            android:id="@+id/login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:hint="請輸入(原生操作)...."
            android:padding="10dp"
            android:singleLine="true"
            android:textSize="15sp" 
            android:drawableLeft="@drawable/ic_search"
           android:layout_marginRight="30dp"
            />
        <ImageView
            android:id="@+id/iv_pwd_clear"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:clickable="true"
            android:src="@drawable/ic_search_delete"
            android:visibility="invisible" />
    </RelativeLayout>
    <View
        android:id="@+id/line"
         android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/black"
        android:layout_below="@id/top"
        android:layout_marginTop="70dp"/>
    <!-- 自定義的具有清除功能的EditText -->
     <com.example.clearedittext.ClearEditText
        android:id="@+id/et_clear"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:background="@drawable/btn_big_normal"
        android:drawableLeft="@drawable/ic_search"
        android:hint="請輸入(自定義操作)...."
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:singleLine="true"
        android:textSize="15sp" />
</RelativeLayout>

第一中實現方式:

public class MainActivity extends Activity {

	private EditText mPswTv;
	private ImageView pwdClean;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mPswTv = (EditText) findViewById(R.id.login_password);
		//清除EditText輸入的圖示
		pwdClean = (ImageView) findViewById(R.id.iv_pwd_clear);
		pwdClean.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mPswTv.setText(null);
			}
		});

		/*
		 * 設定文字輸入變化監聽
		 */
		mPswTv.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(s.length()>0){
					pwdClean.setVisibility(View.VISIBLE);
				}else{
					pwdClean.setVisibility(View.GONE);
				}
			}
		});
	}

第二種實現,是大牛寫的,之後才發現,以下程式碼出自:http://blog.csdn.net/xiaanming/article/details/11066685
通過繼承EditText自定義一個ClearEditText類,在佈局檔案中直接引用即可。

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
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;
public class ClearEditText extends EditText implements  
OnFocusChangeListener, TextWatcher { 
	/**
	 * 刪除按鈕的引用
	 */
	private Drawable mClearDrawable; 

	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,假如沒有設定我們就使用預設的圖片
		mClearDrawable = getCompoundDrawables()[2]; 
		if (mClearDrawable == null) { 
			mClearDrawable = getResources() 
					.getDrawable(R.drawable.ic_search_delete); 
		} 
		mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); 
		setClearIconVisible(false); 
		setOnFocusChangeListener(this); 
		addTextChangedListener(this); 
	} 


	/**
	 * 因為我們不能直接給EditText設定點選事件,所以我們用記住我們按下的位置來模擬點選事件
	 * 當我們按下的位置 在  EditText的寬度 - 圖示到控制元件右邊的間距 - 圖示的寬度  和
	 * EditText的寬度 - 圖示到控制元件右邊的間距之間我們就算點選了圖示,豎直方向沒有考慮
	 */
	@Override 
	public boolean onTouchEvent(MotionEvent event) { 
		if (getCompoundDrawables()[2] != null) { 
			if (event.getAction() == MotionEvent.ACTION_UP) { 
				boolean touchable = event.getX() > (getWidth() 
						- getPaddingRight() - mClearDrawable.getIntrinsicWidth()) 
						&& (event.getX() < ((getWidth() - getPaddingRight())));
				if (touchable) { 
					this.setText(""); 
				} 
			} 
		} 

		return super.onTouchEvent(event); 
	} 

	/**
	 * 當ClearEditText焦點發生變化的時候,判斷裡面字串長度設定清除圖示的顯示與隱藏
	 */
	@Override 
	public void onFocusChange(View v, boolean 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) { 
		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.setAnimation(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;
	}

}

  • setClearIconVisible()方法,設定隱藏和顯示清除圖示的方法,我們這裡不是呼叫setVisibility()方法,setVisibility()這個方法是針對View的,我們可以呼叫setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)來設定上下左右的圖示
  • setOnFocusChangeListener(this) 為輸入框設定焦點改變監聽,如果輸入框有焦點,我們判斷輸入框的值是否為空,為空就隱藏清除圖示,否則就顯示
  • addTextChangedListener(this) 為輸入框設定內容改變監聽,其實很簡單呢,當輸入框裡面的內容發生改變的時候,我們需要處理顯示和隱藏清除小圖示,裡面的內容長度不為0我們就顯示,否是就隱藏,但這個需要輸入框有焦點我們才改變顯示或者隱藏,為什麼要需要焦點,比如我們一個登陸介面,我們儲存了使用者名稱和密碼,在登陸介面onCreate()的時候,我們把我們儲存的密碼顯示在使用者名稱輸入框和密碼輸入框裡面,輸入框裡面內容發生改變,導致使用者名稱輸入框和密碼輸入框裡面的清除小圖示都顯示了,這顯然不是我們想要的效果,所以加了一個是否有焦點的判斷
  • setShakeAnimation(),這個方法是輸入框左右抖動的方法,之前我在某個應用看到過類似的功能,當用戶名錯誤,輸入框就在哪裡抖動,感覺挺好玩的,其實主要是用到一個移動動畫,然後設定動畫的變化率為正弦曲線

下載原始碼