自定义view实现输入框

自定义view实现输入框

    • 输入框

输入框

代码

@SuppressLint("AppCompatCustomView")
public class CleanTextView extends EditText implements View.OnFocusChangeListener, TextWatcher {
    private Drawable compoundDrawable;
    //控制是否获取焦点
    private boolean isFous;

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

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

    public CleanTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        //获取textView上下左右四个图片的位子
        Drawable[] compoundDrawables = getCompoundDrawables();
        //获取右面图片的位子
        compoundDrawable = compoundDrawables[2];
        if (compoundDrawable == null){
            //加载本地图片
            compoundDrawable = getResources().getDrawable(R.mipmap.ppp);
        }
        //确定图片的位子
        compoundDrawable.setBounds(0,0,compoundDrawable.getIntrinsicWidth(),compoundDrawable.getIntrinsicHeight());
        //初始化监听 焦点事件监听
        setOnFocusChangeListener(this);

        //字体监听
        addTextChangedListener(this);
        //控制图片显隐
        setCompoundIconVisibly(false);

    }

    private void setCompoundIconVisibly(boolean isvisibly) {
        Drawable drawable = isvisibly ? compoundDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0],getCompoundDrawables()[1],drawable,getCompoundDrawables()[3]);
    }

    @Override
    public void onFocusChange(View v, boolean isFous) {
        //焦点
        this.isFous = isFous;
        if (!isFous){
            setCompoundIconVisibly(false);
        }else if (this.getText().toString().length() > 0){
            setCompoundIconVisibly(true);
        }
    }

    @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 (s.length() > 0 && isFous){
            setCompoundIconVisibly(true);
        }else{
            setCompoundIconVisibly(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                boolean b = (event.getX() > getWidth() - getTotalPaddingRight()) && (event.getX() < getWidth() - getPaddingRight());
                if (b){
                    this.setText("");
                }
                break;
        }
        return super.onTouchEvent(event);
    }
}

效果图
自定义view实现输入框_第1张图片

你可能感兴趣的:(自定义view实现输入框)