TextView源码(onMeasure)

TextView源码

记录一些问题,以后来看,现在看得有点晕

  1. 自适应,设置可点击文字,点击之后字号变小;添加includeFontPadding=false之后可以暂时解决,但是如果文本很长,原来的框显示不下的话,会截断前面的。猜测是setMovementMethod(LinkMovementMethod.getInstance())的原因,但具体原因未知
  2. 自适应,maxLines=2在两行还未占满之前通过append()添加文字字号会变小,原因未知;append()之后调用requestlayout()可以解决
  3. 行距,1.5倍实际看起来是两倍不止,看许多说法是字体的问题,打印了FontMetrics的参数,topascent之间bottomdescent之间还有比较长的距离,leading好像一直是0,设不设置行间距没差,另外就是includeFontPadding为看不出来有什么效果;据说,FontMetrics是系统决定的,所以,要么重写onDraw方法,否则无法解决行间距和实际预期不符的问题

onMeasure()

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        BoringLayout.Metrics boring = UNKNOWN_BORING;
        BoringLayout.Metrics hintBoring = UNKNOWN_BORING;

        if (mTextDir == null) {
            mTextDir = getTextDirectionHeuristic();
        }

        int des = -1;
        boolean fromexisting = false;
        final float widthLimit = (widthMode == MeasureSpec.AT_MOST)
                ?  (float) widthSize : Float.MAX_VALUE;

        //宽度是精确模式,父容器给的宽度当作当前TextView的宽度;
        if (widthMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            width = widthSize;
        } else {
            if (mLayout != null && mEllipsize == null) {
                des = desired(mLayout);
            }

            if (des < 0) {
                boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
                if (boring != null) {
                    mBoring = boring;
                }
            } else {
                fromexisting = true;
            }

            if (boring == null || boring == UNKNOWN_BORING) {
                if (des < 0) {
                    des = (int) Math.ceil(Layout.getDesiredWidthWithLimit(mTransformed, 0,
                            mTransformed.length(), mTextPaint, mTextDir, widthLimit));
                }
                width = des;
            } else {
                width = boring.width;
            }

            final Drawables dr = mDrawables;
            if (dr != null) {
                width = Math.max(width, dr.mDrawableWidthTop);
                width = Math.max(width, dr.mDrawableWidthBottom);
            }

            if (mHint != null) {
                int hintDes = -1;
                int hintWidth;

                if (mHintLayout != null && mEllipsize == null) {
                    hintDes = desired(mHintLayout);
                }

                if (hintDes < 0) {
                    hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring);
                    if (hintBoring != null) {
                        mHintBoring = hintBoring;
                    }
                }

                if (hintBoring == null || hintBoring == UNKNOWN_BORING) {
                    if (hintDes < 0) {
                        hintDes = (int) Math.ceil(Layout.getDesiredWidthWithLimit(mHint, 0,
                                mHint.length(), mTextPaint, mTextDir, widthLimit));
                    }
                    hintWidth = hintDes;
                } else {
                    hintWidth = hintBoring.width;
                }

                if (hintWidth > width) {
                    width = hintWidth;
                }
            }

            width += getCompoundPaddingLeft() + getCompoundPaddingRight();

            if (mMaxWidthMode == EMS) {
                width = Math.min(width, mMaxWidth * getLineHeight());
            } else {
                width = Math.min(width, mMaxWidth);
            }

            if (mMinWidthMode == EMS) {
                width = Math.max(width, mMinWidth * getLineHeight());
            } else {
                width = Math.max(width, mMinWidth);
            }

            // Check against our minimum width
            width = Math.max(width, getSuggestedMinimumWidth());

            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(widthSize, width);
            }
        }

        int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight();
        int unpaddedWidth = want;

        if (mHorizontallyScrolling) want = VERY_WIDE;

        int hintWant = want;
        int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth();

        if (mLayout == null) {
            makeNewLayout(want, hintWant, boring, hintBoring,
                          width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
        } else {
            final boolean layoutChanged = (mLayout.getWidth() != want) || (hintWidth != hintWant)
                    || (mLayout.getEllipsizedWidth()
                            != width - getCompoundPaddingLeft() - getCompoundPaddingRight());

            final boolean widthChanged = (mHint == null) && (mEllipsize == null)
                    && (want > mLayout.getWidth())
                    && (mLayout instanceof BoringLayout
                            || (fromexisting && des >= 0 && des <= want));

            final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum);

            if (layoutChanged || maximumChanged) {
                if (!maximumChanged && widthChanged) {
                    mLayout.increaseWidthTo(want);
                } else {
                    makeNewLayout(want, hintWant, boring, hintBoring,
                            width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
                }
            } else {
                // Nothing has changed
            }
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            height = heightSize;
            mDesiredHeightAtMeasure = -1;
        } else {
            int desired = getDesiredHeight();

            height = desired;
            mDesiredHeightAtMeasure = desired;

            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(desired, heightSize);
            }
        }

        int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom();
        if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) {
            unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum));
        }

        /*
         * We didn't let makeNewLayout() register to bring the cursor into view,
         * so do it here if there is any possibility that it is needed.
         */
        if (mMovement != null
                || mLayout.getWidth() > unpaddedWidth
                || mLayout.getHeight() > unpaddedHeight) {
            registerForPreDraw();
        } else {
            scrollTo(0, 0);
        }

        setMeasuredDimension(width, height);
    }

该方法测量控件的宽高。

计算宽度的逻辑:

宽度是精确模式,父容器给的宽度当作当前TextView的宽度;

宽度不是精确模式:

​ 计算desired,如果文字不超过一行,宽度为desired;

​ 如果文字超过一行:

​ 判断boring,这里我的理解是text的内容是不是普通text,因为可能有换行,而且是1个字就换行,

​ 如果boring为null,计算DesiredWidthWithLimit

​ 如果boring不为null,width=boring.width

到这里也就基本计算出文字的宽度了,接下来还要考虑drawable、hit、padding、是否可滑动等,一步步计算控件宽度

setLineSpacing()

写标准文字控件的时候,发现设置1.5倍的行距视觉上看起来像是两倍以上,所以比较好奇调用了这个方法之后会发生什么

代码只有几行

public void setLineSpacing(float add, float mult) {
    if (mSpacingAdd != add || mSpacingMult != mult) {
        mSpacingAdd = add;
        mSpacingMult = mult;

        if (mLayout != null) {
            nullLayouts(); //将一些参数都置null
            requestLayout(); //遍历视图树重新布局
            invalidate(); //请求重绘View树
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中,可以使用SpannableStringBuilder类来实现TextView中嵌套TextView的效果。具体步骤如下: 1. 创建一个外部的TextView,设置它的text为一个SpannableStringBuilder对象。 2. 在SpannableStringBuilder对象中插入需要嵌套的TextView,使用setSpan()方法将TextView对象作为参数传入。 3. 设置TextView的布局参数,使其可以适应外部TextView的尺寸。 以下是示例代码: ``` TextView outerTextView = findViewById(R.id.outer_text_view); SpannableStringBuilder builder = new SpannableStringBuilder(); TextView innerTextView = new TextView(this); innerTextView.setText("Inner TextView"); builder.append("Outer TextView "); builder.setSpan(new MySpannable(innerTextView), builder.length(), builder.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); outerTextView.setText(builder); outerTextView.setMovementMethod(LinkMovementMethod.getInstance()); class MySpannable extends ClickableSpan { private TextView textView; public MySpannable(TextView textView) { this.textView = textView; this.textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } @Override public void onClick(View widget) { // Do something when inner TextView is clicked } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(ds.linkColor); // Use link color for inner TextView ds.setUnderlineText(false); } @Override public void drawBackground(Canvas canvas, Paint paint, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) { // Do not draw background for inner TextView } } ``` 在上面的代码中,我们创建了一个内部TextView对象,并将它作为参数传入MySpannable类的构造方法中。然后,使用setSpan()方法将MySpannable对象插入到SpannableStringBuilder对象中,从而实现了TextView的嵌套效果。 注意,为了使内部TextView能够响应点击事件,需要调用setMovementMethod()方法并传入LinkMovementMethod.getInstance()。此外,还需要重写MySpannable类的updateDrawState()方法来设置内部TextView的颜色,以及重写drawBackground()方法来取消内部TextView的背景色。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值