Why does TextView have end padding when multi line?

前端 未结 4 783
执念已碎
执念已碎 2021-02-07 06:27

If you have a TextView with layout_width=\"wrap_content\" and it has to wrap to a second line to contain the text, then it will size its width to use up all of the

4条回答
  •  清歌不尽
    2021-02-07 07:06

    At first, when seeing your post, i thought that the problem was because standard Android TextView have some default padding defined in their base style. If one wants to remove it, ones can try it something like :

    android:paddingEnd="0dp"
    

    or

    android:paddingRight="0dp"
    

    As your post has been updated, I understand that your problem does not comes from padding, but from word wrapping. Indeed, when there are several lines to display, Android TextView use the whole available space in width.

    As stated in this post, there is no standard solution for this and you will need to customize your text view to fix its width after filling it.

    Overriding onMeasure method of your textView like below shoud work (inspired from "sky" answer) :

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        int specModeW = MeasureSpec.getMode(widthMeasureSpec);
        if (specModeW != MeasureSpec.EXACTLY) {
            Layout layout = getLayout();
            int linesCount = layout.getLineCount();
            if (linesCount > 1) {
                float textRealMaxWidth = 0;
                for (int n = 0; n < linesCount; ++n) {
                    textRealMaxWidth = Math.max(textRealMaxWidth, layout.getLineWidth(n));
                }
                int w = (int) Math.ceil(textRealMaxWidth);
                if (w < getMeasuredWidth()) {
                    super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST),
                            heightMeasureSpec);
                }
            }
        }
    }
    

提交回复
热议问题