实现EditText带清除图标以及监听文本输入并显示或隐藏某个按钮(View)

效果图:

实现EditText带清除图标以及监听文本输入并显示或隐藏某个按钮(View)_第1张图片

实现EditText带清除图标以及监听文本输入并显示或隐藏某个按钮(View)_第2张图片

实现EditText带清除图标以及监听文本输入并显示或隐藏某个按钮(View)_第3张图片

实现EditText带清除图标以及监听文本输入并显示或隐藏某个按钮(View)_第4张图片

自定义EditText:ClearEditText.java
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import test.timertest.com.inputtexthelper.R;


public class ClearEditText extends AppCompatEditText implements View.OnTouchListener, View.OnFocusChangeListener, TextWatcher {

    private Drawable mClearIcon;

    private OnTouchListener mOnTouchListener;

    private OnFocusChangeListener mOnFocusChangeListener;

    public ClearEditText(Context context) {
        super(context);
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    private void initialize(final Context context) {

        //R.mipmap.input_delete 清除图标
        final Drawable drawable = ContextCompat.getDrawable(context, R.mipmap.input_delete);

        //Wrap the drawable so that it can be tinted pre Lollipop
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        //DrawableCompat.setTint(wrappedDrawable, getCurrentHintTextColor());
        mClearIcon = wrappedDrawable;
        mClearIcon.setBounds(0, 0, mClearIcon.getIntrinsicWidth(), mClearIcon.getIntrinsicHeight());
        setClearIconVisible(false);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
        super.addTextChangedListener(this);

        ViewCompat.setBackgroundTintList(this, ColorStateList.valueOf(0x99000000));
    }

    private void setClearIconVisible(final boolean visible) {
        if (mClearIcon.isVisible() == visible) return;

        mClearIcon.setVisible(visible, false);
        final Drawable[] compoundDrawables = getCompoundDrawables();
        setCompoundDrawables(
                compoundDrawables[0],
                compoundDrawables[1],
                visible ? mClearIcon : null,
                compoundDrawables[3]);
    }

    @Override
    public void setOnFocusChangeListener(final OnFocusChangeListener onFocusChangeListener) {
        mOnFocusChangeListener = onFocusChangeListener;
    }

    @Override
    public void setOnTouchListener(final OnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
    }

    /**
     * {@link View.OnFocusChangeListener}
     */

    @Override
    public void onFocusChange(final View view, final boolean hasFocus) {
        if (hasFocus && getText() != null) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
        if (mOnFocusChangeListener != null) {
            mOnFocusChangeListener.onFocusChange(view, hasFocus);
        }
    }

    /**
     * {@link View.OnTouchListener}
     */

    @Override
    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        final int x = (int) motionEvent.getX();
        if (mClearIcon.isVisible() && x > getWidth() - getPaddingRight() - mClearIcon.getIntrinsicWidth()) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                setText("");
            }
            return true;
        }
        return mOnTouchListener != null && mOnTouchListener.onTouch(view, motionEvent);
    }

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

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (isFocused()) {
            setClearIconVisible(s.length() > 0);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
InputTextHelper.java
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class InputTextHelper implements TextWatcher {

    /**
     * 操作按钮的View(需要显示/隐藏的view)
     */
    private View mView;

    /**
     * 禁用后是否设置半透明度
     */
    private boolean isAlpha;

    /**
     * EditText集合
     */
    private List mViewSet;

    public InputTextHelper(View view) {
        this(view, false);
    }

    /**
     * 构造函数
     *
     * @param view   根据 EditText 输入是否为空来判断启用或禁用这个 View
     * @param alpha  是否需要设置透明度
     */
    public InputTextHelper(View view, boolean alpha) {
        if (view == null) {
            throw new IllegalArgumentException("The view is empty");
        }
        mView = view;
        isAlpha = alpha;
    }

    /**
     * 添加 EditText
     *
     * @param views  传入单个或者多个 EditText
     */
    public void addViews(EditText... views) {
        if (views == null) {
            return;
        }

        if (mViewSet == null) {
            mViewSet = new ArrayList<>(views.length - 1);
        }

        for (EditText view : views) {
            view.addTextChangedListener(this);
            mViewSet.add(view);
        }
        afterTextChanged(null);
    }

    /**
     * 移除 EditText 监听,避免内存泄露
     */
    public void removeViews() {
        if (mViewSet == null) {
            return;
        }

        for (EditText view : mViewSet) {
            view.removeTextChangedListener(this);
        }
        mViewSet.clear();
        mViewSet = null;
    }

    /**
     * {@link TextWatcher}
     */

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        if (mViewSet == null) {
            return;
        }

        for (EditText view : mViewSet) {
            if ("".equals(view.getText().toString())) {
                setEnabled(false);
                return;
            }
        }
        setEnabled(true);
    }

    /**
     * 设置 View 的事件
     *
     * @param enabled 启用或者禁用 View 的事件
     */
    public void setEnabled(boolean enabled) {
        if (enabled == mView.isEnabled()) {
            return;
        }

        if (enabled) {
            //启用View的事件
            mView.setEnabled(true);
            if (isAlpha) {
                //设置不透明
                mView.setAlpha(1f);
            }
        }else {
            //禁用View的事件
            mView.setEnabled(false);
            if (isAlpha) {
                //设置半透明
                mView.setAlpha(0.5f);
            }
        }
    }
}
color.xml


    #FFFFFF
    #000000
    #5A8DDF

    
    #1976d2
    
    #DDDDDD
    
    #ECECEC
drawable文件:selector_button.xml




    
    
        
            
            
        
    

    
    
        
            
            
        
    

    
    
        
            
            
        
    

    
    
        
            
            
        
    

布局文件:activity_main.xml



    

    

    

    
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import test.timertest.com.inputtexthelper.R;

public class MainActivity extends AppCompatActivity {

    private EditText mPhoneView, mPasswordView;

    private Button loginBt;

    private InputTextHelper mInputTextHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPhoneView = (EditText) findViewById(R.id.phone_et);
        mPasswordView = (EditText) findViewById(R.id.password_et);
        loginBt = (Button) findViewById(R.id.login_bt);
        loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "登录", Toast.LENGTH_SHORT).show();
            }
        });

        mInputTextHelper = new InputTextHelper(loginBt);
        mInputTextHelper.addViews(mPhoneView, mPasswordView);
    }

    /**
     * 移除 EditText 监听,避免内存泄露
     */
    @Override
    protected void onDestroy() {
        mInputTextHelper.removeViews();
        super.onDestroy();
    }
}

 

你可能感兴趣的:(Android)