[好用的小控件] 自带清除的EditText

public class ClearableTextView extends FrameLayout implements OnClickListener, TextWatcher, OnFocusChangeListener {

    private EditText mEditText;
    private ImageButton mClearButton;

    public ClearableTextView(Context context) {
        super(context);
        initViews(context);
    }

    public ClearableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }

    public ClearableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initViews(context);
    }

    private void initViews(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View root = inflater.inflate(R.layout.layout_clearable_textview, null);
        mEditText = (EditText) root.findViewById(android.R.id.edit);
        mClearButton = (ImageButton) root.findViewById(android.R.id.button1);

        mEditText.addTextChangedListener(this);
        mEditText.setOnFocusChangeListener(this);
        mClearButton.setOnClickListener(this);

        LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER_VERTICAL;
        addView(root, lp);

        displayClearButton(false);
    }

    @Override
    public void onClick(View v) {
        if (mClearButton == v) {
            mEditText.getText().clear();
            displayClearButton(false);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        refreshClearButtonState();
    }

    @Override
    public void afterTextChanged(Editable s) {
        refreshClearButtonState();
    }

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

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

    private void refreshClearButtonState() {
        String text = mEditText.getText().toString();
        boolean hasFocus = mEditText.isFocused();
        if (!TextUtils.isEmpty(text) && hasFocus) {
            displayClearButton(true);
        } else {
            displayClearButton(false);
        }
    }

    public void displayClearButton(boolean show) {
        if (show) {
            if (mClearButton.getVisibility() != View.VISIBLE)
                mClearButton.setVisibility(View.VISIBLE);
        } else if (mClearButton.getVisibility() != View.INVISIBLE) {
            mClearButton.setVisibility(View.INVISIBLE);
        }
    }
}


iPhone好像自带这样的控件,有时候使用起来比较方便,我们大Android怎么会无法实现这种功能呢?

我的实现比较简单,布局由一个EditText和Button组成,清除按钮会在(输入框中有内容 && 输入框获得了焦点)的情况下出现。


你可能感兴趣的:([好用的小控件] 自带清除的EditText)