美文网首页
一个可控长度,带下划线的自定义Edittext

一个可控长度,带下划线的自定义Edittext

作者: kksoCoud | 来源:发表于2017-07-03 20:57 被阅读85次

    看到带下划线的Edittext,估计大家会嗤之以鼻,Edittext本就自带下划线,但我要实现的是下划线是有间隔的。我们先看看效果,如果觉得有值得学习的地方再往下看,省得浪费时间。


    下划线EdittextView.jpg

    相信各位看官看了效果,应该不会觉得那么简单了吧,但其实也不难。我们可以通过继承Edittext自定义View来实现。为啥非得继承Edittext呢?原因很简单,系统提供的Edittext可以获取键盘的输入,省去了我们不少麻烦事。开始我也是想通过继承View来实现的,显得更高大上,有逼可装。但在适配过程中发现,国内有的手机厂商的手机我们是监听不到用户键盘点击事件的,除了删除等一些公用的(估计是为了用户信息安全考虑),因此也就放弃了这种实现方式。啰嗦了半天,现在我们正式进入正题(下面是实现核心代码):

    private void init(AttributeSet attrs) {
        density = getContext().getResources().getDisplayMetrics().density;
        initDefaultAttributes();
        initCustomAttributes(attrs);
        initDataStructures();
        initPaint();
    }
    
    private void initDataStructures() {
        underlines = new Underline[underlineAmount];
    }
    
    private void initPaint() {
        underlinePaint = new Paint();
        underlinePaint.setColor(underlineColor);
        underlinePaint.setStrokeWidth(underlineStrokeWidth);
        underlinePaint.setStyle(Paint.Style.STROKE);
        textPaint = new Paint();
        textPaint.setTextSize(textSize);
        textPaint.setColor(textColor);
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Paint.Align.CENTER);
        backgroundPaint = new Paint();
        backgroundPaint.setColor(backgroundColor);
    }
    
    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
        super.onSelectionChanged(selStart, selEnd);
        if (selStart == selEnd){
            //使光标一直处于文末
            setSelection(getText().length());
        }
    }
    
    //设置下划线数量
    public void setCodes(int codes) {
        underlineAmount = codes;
        initDataStructures();
    }
    
    private void initCustomAttributes(AttributeSet attrs) {
        TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.EditTextView);
        try {
            underlineColor = attributes.getColor(R.styleable.EditTextView_underline_color, underlineColor);
            underlineAmount = attributes.getInt(R.styleable.EditTextView_codes, underlineAmount);
            textColor = attributes.getInt(R.styleable.EditTextView_text_color, textColor);
            textSize = attributes.getDimension(R.styleable.EditTextView_text_size, textSize);
            backgroundColor = attributes.getColor(R.styleable.EditTextView_background_color, backgroundColor);
        } finally {
            attributes.recycle();
        }
    }
    
    private void initDefaultAttributes() {
        underlineStrokeWidth = 2 * density;
        underlineWidth = 35 * density;
        underlineReduction = 5 * density;
        textSize = 15 * density;
        textMarginBottom = 15 * density;
        underlineColor = Color.parseColor("#cccccc");
        textColor = Color.parseColor("#000000");
        viewHeight = 50 * density;
        underlineAmount = DEFAULT_CODES;
        backgroundColor = Color.parseColor("#ffffff");
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged((int) ((underlineWidth + underlineReduction) * underlineAmount - underlineReduction), (int) viewHeight, oldw, oldh);
        height = h;
        width = w;
        initRect();
        initUnderline();
    }
    
    private void initRect() {
        rectBackground = new RectF(0, 0, width, height);
    }
    
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension((int) ((underlineWidth + underlineReduction) * underlineAmount - underlineReduction), (int) viewHeight);
    }
    
    private void initUnderline() {
        for (int i = 0; i < underlineAmount; i++) {
            underlines[i] = createPath(i, underlineWidth);
        }
    }
    
    private Underline createPath(int position, float sectionWidth) {
        float fromX = (sectionWidth + underlineReduction) * (float) position;
        return new Underline(fromX, height, fromX + sectionWidth, height);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        //绘制白色背景将原有edittext遮住
        canvas.drawRect(rectBackground, backgroundPaint);
        for (int i = 0; i < underlines.length; i++) {
            Underline sectionpath = underlines[i];
            float fromX = sectionpath.getFromX();
            float fromY = sectionpath.getFromY();
            float toX = sectionpath.getToX();
            float toY = sectionpath.getToY();
            drawSection(fromX, fromY, toX, toY, canvas);
        }
        for (int i = 0; i < textLength; i++) {
            drawCharacter(underlines[i].getFromX(), underlines[i].getToX(), getText().toString().charAt(i), canvas);
        }
    }
    
    //绘制下划线
    private void drawSection(float fromX, float fromY, float toX, float toY, Canvas canvas) {
        Paint paint = underlinePaint;
        canvas.drawLine(fromX, fromY, toX, toY, paint);
    }
    
    //绘制文字
    private void drawCharacter(float fromX, float toX, Character character, Canvas canvas) {
        float actualWidth = toX - fromX;
        float centerWidth = actualWidth / 2;
        float centerX = fromX + centerWidth;
        canvas.drawText(String.valueOf(character), centerX, height - textMarginBottom, textPaint);
    }
    
    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        this.textLength = text.toString().length();
        Editable text1 = getText();
        if (text1.length() > underlineAmount){
            setText(text1.subSequence(0, underlineAmount));
            this.textLength = underlineAmount;
        }
    }
    
        /**
         * 下划线
         */
        class Underline {
    
            float fromX;
            float fromY;
            float toX;
            float toY;
    
            public Underline() {
            }
    
            public Underline(float fromX, float fromY, float toX, float toY) {
                this.fromX = fromX;
                this.fromY = fromY;
                this.toX = toX;
                this.toY = toY;
            }
    
            public void from(float x, float y) {
                this.fromX = x;
                this.fromY = y;
            }
    
            public void to(float x, float y) {
                this.toX = x;
                this.toY = y;
            }
    
            public float getFromX() {
                return fromX;
            }
    
            public void setFromX(float fromX) {
                this.fromX = fromX;
            }
    
            public float getFromY() {
                return fromY;
            }
    
            public void setFromY(float fromY) {
                this.fromY = fromY;
            }
    
            public float getToX() {
                return toX;
            }
    
            public void setToX(float toX) {
                this.toX = toX;
            }
    
            public float getToY() {
                return toY;
            }
    
            public void setToY(float toY) {
                this.toY = toY;
            }
        }
    
    <declare-styleable name="EditTextView">
        <!--下划线颜色-->
        <attr name="underline_color" format="color" />
        <!--文字颜色-->
        <attr name="text_color" format="color" />
        <!--下划线数量-->
        <attr name="codes" format="integer" />
        <!--字体大小-->
        <attr name="text_size" format="dimension"/>
        <!--背景颜色-->
        <attr name="background_color" format="color"/>
    </declare-styleable>
    

    没错就是这么简单,一个能够控制输入数量、下划线颜色可设置且携带所有Edittext属性的自定义View就这么实现了。若要查看源码可访问我的仓库。欢迎Star、Fork或者有更好的实现方式的建议可在下面留言,谢谢。

    相关文章

      网友评论

          本文标题:一个可控长度,带下划线的自定义Edittext

          本文链接:https://www.haomeiwen.com/subject/rtmzcxtx.html