自定义EditText清除功能实现

2017-06-12  本文已影响0人  青见仔

效果图:

GIF.gif

1. 编写xml布局 代码 如下:

<com.zjq.cleareditextview.ClearEditTextView
            android:id="@+id/et_username"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_marginTop="5dp"
            android:hint="QQ号/手机号/邮箱号"
            android:inputType="number"
            android:lines="1"
            android:maxLength="17"
            android:paddingLeft="13dp"
            android:textColorHint="#b9b7b7"
            android:textSize="16sp" />
注意这里的 com.zjq.clearedittextview.ClearEditTextView 要与你的 ClearEditTextView类包名相同

2.创建ClearEditTextView类并继承EditText

public class ClearEditTextView extends EditText implements View.OnFocusChangeListener,TextWatcher {

// 右边的删除按钮
private Drawable mClearDrawable;

public ClearEditTextView(Context context) {
    this(context, null);
}

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

public ClearEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    //获取右边删除按钮
    mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);
    //设置删除按钮的边界
    mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());

    //设置默认隐藏删除按钮
    setClearIcon(false);

    //监听EditText焦点变化 ,根据text长度控制删除按钮的显示 .隐藏
    setOnFocusChangeListener(this);
    //监听文本内容变化
    addTextChangedListener(this);
}

/**
 * 控制EditText右边制删除按钮的显示、隐藏
 */
/**
 * 控制EditText右边制删除按钮的显示、隐藏
 */
private void setClearIcon(boolean isShow) {
    Drawable rightDrawable = isShow ? mClearDrawable : null;
    setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1],
            rightDrawable, getCompoundDrawables()[3]);
}  }
注意这里的R.drawable.delete_selector。

3.在miamap下面放入两张删除图片

一张是默认显示的图片

命名为:search_clear_normal.png

一张是按下删除按钮显示的图片

命名为:search_clear_pressed

4.在drawable文件下创建delete_selector.xml文件

<?xml version="1.0" encoding="utf-8"?>
< selector xmlns:android="http://schemas.android.com/apk/res/android">

<!--按下状态-->
<item android:state_pressed="true" android:drawable="@mipmap/search_clear_pressed" />

<!--默认显示-->
<item android:drawable="@mipmap/search_clear_normal" />

</selector>

设置引用mipmap下面的图片。
到此已经可以实现清除功能了!!
上一篇 下一篇

猜你喜欢

热点阅读