自定義EditText,帶清除按鈕和底部線條

由于項目要求,需要滿足UI小姐姐設(shè)計的輸入框樣式,所以要重寫EditText,擴展自定義樣式,效果如下:


20190621-1235126.gif

不多說啦,直接上碼:

package com.lib.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.reflect.Field;

/**
 * 帶底部線條和右邊清除icon的輸入框
 */
@SuppressLint("AppCompatCustomView")
public class GeneralEditText extends EditText implements View.OnTouchListener, View.OnFocusChangeListener, TextWatcher {

    private static final String TAG = "GeneralEditText";
    private static final String NAME_SPACE = "http://schemas.android.com/apk/res/android";
    private Paint mPaint;
    private Drawable mClearTextIcon;
    private OnFocusChangeListener mOnFocusChangeListener;
    private OnTouchListener mOnTouchListener;
    // 設(shè)置橫線默認顏色
    private static final String NO_FOCUS_COLOR_STRING = "#FFCBD1D5";
    private static final String ON_FOCUS_COLOR_STRING = "#6A6969";
    private int defaultLineColor = Color.parseColor(NO_FOCUS_COLOR_STRING);
    private int onFocusLineColor = Color.parseColor(ON_FOCUS_COLOR_STRING);
    private int lineColor = defaultLineColor;
    // 提示文字的默認顏色和線默認顏色一樣
    private int hintTextColor = defaultLineColor;
    // 寬度為3
    private float strokeWidth = 3f;

    public GeneralEditText(final Context context) {
        super(context);
        init(context, null);
    }

    public GeneralEditText(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public GeneralEditText(final Context context, final AttributeSet attrs, final int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化
     * @param context
     * @param attrs
     * <p>
     *     ContextCompat.getColor(context, R.color.color_FFCBD1D5);
     * </p>
     */
    private void init(Context context, AttributeSet attrs) {
        initAttributeFromXml(attrs);

        // 初始化畫筆
        mPaint = new Paint();
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(lineColor);

        // 右邊的刪除圖片
        final Drawable drawable = ContextCompat.getDrawable(context, R.drawable.icon_enter_delete);
        mClearTextIcon = drawable;
        int intrinsicWidth = mClearTextIcon.getIntrinsicWidth();
        int intrinsicHeight =  mClearTextIcon.getIntrinsicHeight();
        float fontSize = this.getTextSize();
        float wRatio = (fontSize / intrinsicWidth) > 1 ? 1 : (fontSize / intrinsicWidth);
        float hRatio = (fontSize / intrinsicHeight) > 1 ? 1 : (fontSize / intrinsicHeight);
        int right = (int) (intrinsicWidth * wRatio);
        int bottom = (int) (intrinsicHeight * hRatio);
        mClearTextIcon.setBounds(0, 0, right, bottom);

        setClearIconVisible(false);
        setBackground(null);
        setHintTextColor(hintTextColor);
        addTextChangedListener(this);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
    }

    /**
     * 初始化屬性
     * @param attrs
     */
    private void initAttributeFromXml(AttributeSet attrs) {
        if (attrs == null) {
            return;
        }

        // 光標
        int cursorValue = attrs.getAttributeResourceValue(NAME_SPACE, "textCursorDrawable", -1);
        if (cursorValue == -1) {
            // 設(shè)置默認的光標顏色
            setTextCursorDrawable(R.drawable.cursor_default_color);
        }
        // 提示文字的字體顏色
        int hintValue = attrs.getAttributeResourceValue(NAME_SPACE, "textColorHint", -1);
        if (hintValue != -1) {
            hintTextColor = ContextCompat.getColor(getContext(), hintValue);
        }

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.GeneralEditText);
        if (ta == null) {
            return;
        }
        if (ta.hasValue(R.styleable.GeneralEditText_stroke_width)) {
            strokeWidth = ta.getDimension(R.styleable.GeneralEditText_stroke_width, 3);
        }
        if (ta.hasValue(R.styleable.GeneralEditText_no_focus_line_color)) {
            defaultLineColor = ta.getColor(R.styleable.GeneralEditText_no_focus_line_color, Color.parseColor(NO_FOCUS_COLOR_STRING));
        }
        if (ta.hasValue(R.styleable.GeneralEditText_on_focus_line_color)) {
            onFocusLineColor = ta.getColor(R.styleable.GeneralEditText_on_focus_line_color, Color.parseColor(ON_FOCUS_COLOR_STRING));
        }

        // Recycles the TypedArray, to be re-used by a later caller. After calling
        // this function you must not ever touch the typed array again.
        ta.recycle();
    }

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

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

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            lineColor = onFocusLineColor;
            setClearIconVisible(getText().length() > 0);
        } else {
            lineColor = defaultLineColor;
            setClearIconVisible(false);
        }
        // 重新設(shè)置畫筆的顏色
        mPaint.setColor(lineColor);

        if (mOnFocusChangeListener != null) {
            mOnFocusChangeListener.onFocusChange(v, hasFocus);
        }
    }

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

    @Override
    public final void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if (isFocused()) {
            setClearIconVisible(text.length() > 0);
        }
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 設(shè)置右邊刪除icon的顯示
     * @param visible
     */
    private void setClearIconVisible(final boolean visible) {
        mClearTextIcon.setVisible(visible, false);
        final Drawable[] compoundDrawables = getCompoundDrawables();
        setCompoundDrawables(
                compoundDrawables[0],
                compoundDrawables[1],
                visible ? mClearTextIcon : null,
                compoundDrawables[3]);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 獲取控件寬度
        int w = this.getWidth();
        // 獲取控件高度
        int h = this.getHeight();
        // X方向可滑動的距離
        int sx = this.getScrollX();
        // Y方向可滑動的距離
        int sy = this.getScrollY();
        // 獲取左邊padding
        int paddingLeft = this.getPaddingLeft();
        // 獲取右邊padding
        int paddingRight = this.getPaddingRight();
        // 獲取底部的padding
        int paddingBottom = this.getPaddingBottom();

        float y = paddingBottom > 0 ? h - paddingBottom / 2 + sy : h + sy;
        float startX = paddingLeft;
        float startY = y;
        float stopX = w + sx - paddingRight;
        float stopY = y;

        /**
         * 從下面畫線
         * canvas.drawLine(float startX, float startY, float stopX, float stopY, Paint paint);
         */
        canvas.drawLine(startX, startY, stopX , stopY, mPaint);
    }

    /**
     * 設(shè)置光標的顏色
     */
    private void setTextCursorDrawable(int drawableId) {
        try {
            // 獲取字段
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            // 設(shè)置字段可以被訪問
            f.setAccessible(true);
            f.set(this, drawableId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

自定義屬性,attrs.xml

    <declare-styleable name="GeneralEditText">
        <attr name="stroke_width" format="dimension"/>
        <attr name="on_focus_line_color" format="color"/>
        <attr name="no_focus_line_color" format="color"/>
    </declare-styleable>

在布局件中使用

    <com.lib.widget.GeneralEditText
        android:id="@+id/et_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dimen_55"
        android:layout_marginRight="@dimen/dimen_55"
        android:layout_marginTop="@dimen/dimen_55"
        android:textSize="@dimen/font_28"
        android:hint="@string/input_mobile"
        android:inputType="phone"
        android:maxLines="1"/>

完結(jié)。。。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容