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

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值