Android中自定义EditText控件(自带清除功能等)

来源:互联网 发布:win10玩dnf卡顿优化 编辑:程序博客网 时间:2024/05/11 16:41

自定义EditText代码如下
public class CustomEditText extends EditText implements
OnFocusChangeListener,
TextWatcher {

private Drawable drawable;// 定义一个 Drawable变量用于接收 EditText右private boolean hasFocus;// 定义一个焦点变量public CustomEditText(Context context, AttributeSet attrs, int defStyle) {    super(context, attrs, defStyle);    setEditText();}public CustomEditText(Context context, AttributeSet attrs) {    this(context, attrs, android.R.attr.editTextStyle);}public CustomEditText(Context context) {    this(context, null);}private void setEditText() {    // 获得EditText右边的值    drawable = getCompoundDrawables()[2];    if (drawable == null) {    drawable = getResources().getDrawable(R.drawable.edittext_selector);    }    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),            drawable.getIntrinsicHeight());    setIocnVisable(false);    setOnFocusChangeListener(this);    addTextChangedListener(this);}/** * 当EditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏 */@Overridepublic void onFocusChange(View v, boolean hasFocus) {    this.hasFocus = hasFocus;    if (hasFocus) {        // 去执行一个 一个方法设置图片        setIocnVisable(getText().length() > 0);    }else {        setIocnVisable(false);    }}/** * 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去 *  * @param visible */private void setIocnVisable(boolean visible) {    Drawable right = visible ? drawable : null;    setCompoundDrawables(getCompoundDrawables()[0],        getCompoundDrawables()[1], right, getCompoundDrawables()[3]);}/** * 当输入框里面内容发生变化的时候回调的方法 */@Overridepublic void onTextChanged(CharSequence text, int start, int lengthBefore,        int lengthAfter) {    if (hasFocus) {        setIocnVisable(getText().length() > 0);    }}@Overridepublic boolean onTouchEvent(MotionEvent event) {    if (event.getAction() == MotionEvent.ACTION_UP) {        if (getCompoundDrawables()[2] != null) {            boolean m = event.getX() > (getWidth() - getTotalPaddingRight())                    && (event.getX() < (getWidth() - getPaddingRight()));            if (m) {                setText("");            }        }    }    return super.onTouchEvent(event);}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,        int after) {}@Overridepublic void afterTextChanged(Editable s) {}

}

布局部分代码

<com.haoxianwen.keep.view.CustomEditText        android:id="@+id/username_customEditText"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/logo_id"        android:layout_marginTop="30dp"        android:background="@drawable/et_background"        android:drawableLeft="@drawable/icon_user"        android:drawableRight="@drawable/edittext_selector"        android:ems="10"        android:hint="请输入您的帐号"        android:singleLine="true" />

效果展示

右边的叉号可以清空EditText的内容,输入框中的焦点事件会根据内容来改变!

0 0