Android 监听EditText是否为空,控制按钮是否可用

/**
 * Created by LYQ on 2018/1/29.
 */

public final class TextInputHelper implements TextWatcher {
    private View mMainView;//操作按钮的View
    private List mViewSet;//TextView集合,子类也可以(EditText、TextView、Button)
    private boolean isAlpha;//是否设置透明度

    public TextInputHelper(View view) {
        this(view, true);
    }

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

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

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

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

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

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

    // 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 synchronized void afterTextChanged(Editable s) {
        if (mViewSet == null) return;

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

        setEnabled(true);
    }

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

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

 

使用时:

TextInputHelper helper =new TextInputHelper(mBt_secondactivity_show);
helper.addViews(mEt_secondactivity_text1,mEt_secondactivity_text2,mEt_secondactivity_text3);

你可能感兴趣的:(Android)