1. 程式人生 > >android 帶清除功能的EditText

android 帶清除功能的EditText

先看效果圖

      

當不輸入任何內容時候,右邊的清除圖示不會出現,但是如果只要輸入一個字元以後,清除圖示就會出現,點選清除圖示以後就會清除輸入框當中的內容

首先要自定義一個MyEditView

<span style="font-size:18px;">package com.example.edittextcleardemo;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;

public class MyEditView extends EditText implements TextWatcher,
		OnFocusChangeListener {

	/**
	 * 左右兩側圖片資源
	 */
	private Drawable left, right;
	/**
	 * 是否獲取焦點,預設沒有焦點
	 */
	private boolean hasFocus = false;
	/**
	 * 手指擡起時的X座標
	 */
	private int xUp = 0;
	
	public MyEditView(Context context) {
		this(context, null);
	}

	public MyEditView(Context context, AttributeSet attrs) {
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public MyEditView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initWedgits(attrs);
	}

	/**
	 * 初始化各元件
	 * @param attrs
	 *            屬性集
	 */
	private void initWedgits(AttributeSet attrs) {
		try {
			left = getCompoundDrawables()[0];
			right = getCompoundDrawables()[2];
			initDatas();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化資料
	 */
	private void initDatas() {
		try {
			// 第一次顯示,隱藏刪除圖示
			setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
			addListeners();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增事件監聽
	 */
	private void addListeners() {
		try {
			setOnFocusChangeListener(this);
			addTextChangedListener(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int after) {
		if (hasFocus) {
			if (TextUtils.isEmpty(s)) {
				// 如果為空,則不顯示刪除圖示
				setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
			} else {
				// 如果非空,則要顯示刪除圖示
				if (null == right) {
					right = getCompoundDrawables()[2];
				}
				setCompoundDrawablesWithIntrinsicBounds(left, null, right, null);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		try {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				// 獲取點選時手指擡起的X座標
				xUp = (int) event.getX();
				// 當點選的座標到當前輸入框右側的距離小於等於getCompoundPaddingRight()的距離時,則認為是點選了刪除圖示
				// getCompoundPaddingRight()的說明:Returns the right padding of the view, plus space for the right Drawable if any.
				if ((getWidth() - xUp) <= getCompoundPaddingRight()) {
					if (!TextUtils.isEmpty(getText().toString())) {
						setText("");
					}
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.onTouchEvent(event);
	}

	@Override
	public void afterTextChanged(Editable s) {
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		try {
			this.hasFocus = hasFocus;
			String msg=getText().toString();

			if(hasFocus){
				if(msg.equalsIgnoreCase("")){
					setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
			    }else{
			    	setCompoundDrawablesWithIntrinsicBounds(left, null, right, null);
			    }
			}
			if(hasFocus==false){
				setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//獲取輸入內容
	public String text_String (){
		return getText().toString();
	}
}
</span>

使用的時候只要在需要的佈局中引入該控制元件即可:
<span style="font-size:18px;"><com.example.edittextcleardemo.MyEditView
                    android:id="@+id/user_name"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/imageView1"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="15dip"
                    android:layout_toRightOf="@+id/imageView1"
                 <span style="color:#ff0000;">   android:background="@drawable/edit_input_rectangle"</span>
                    <span style="color:#ff0000;">android:drawableRight="@drawable/clear_normal_list"</span>
                    android:hint="請輸入使用者名稱"
                    android:textCursorDrawable="@null"
                    android:textSize="14sp" >
                </com.example.edittextcleardemo.MyEditView></span>

這個輸入框是圓角的,原因是引用了樣式android:background="@drawable/edit_input_rectangle"
這個樣式的定義是edit_input_rectangle.xml放在drawable檔案當中
</pre><pre name="code" class="plain">
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- 圓角 -->
    <corners android:radius="5dp" />
  
    <!-- 大小 -->
    <size android:height="40dp" />
    <!-- 填充 -->

    <solid android:color="#FFFFFF" />

    <!-- 描邊 -->
    <stroke
        android:width="1dp"
        android:color="@android:color/white" />

</shape></span>


<span style="font-size:18px;">clear_normal_list是清除圖示</span>


程式碼下載地址:http://download.csdn.net/detail/xubeiqiannian/8765683