TextView works wrong with breakStrategy=“balanced” and layout_width=“wrap_content”

后端 未结 2 794
慢半拍i
慢半拍i 2021-02-04 15:21

I have such layout (I\'ve removed some attributes, cause they really doesn\'t matter, full demo project is here):



        
2条回答
  •  醉梦人生
    2021-02-04 15:53

    This happens because when TextView calculates its width it measure all text as 1 line (in your case) and on this step it knows nothing about android:breakStrategy. So it is trying to utilize all available space to render as much text on first line as it can.

    To get more details, please check method int desired(Layout layout) here

    To fix it you can use this class:

    public class MyTextView extends TextView {
    public MyTextView(Context context) {
        super(context);
    }
    
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        Layout layout = getLayout();
        if (layout != null) {
            int width = (int) Math.ceil(getMaxLineWidth(layout))
                    + getCompoundPaddingLeft() + getCompoundPaddingRight();
            int height = getMeasuredHeight();
            setMeasuredDimension(width, height);
        }
    }
    
    private float getMaxLineWidth(Layout layout) {
        float max_width = 0.0f;
        int lines = layout.getLineCount();
        for (int i = 0; i < lines; i++) {
            if (layout.getLineWidth(i) > max_width) {
                max_width = layout.getLineWidth(i);
            }
        }
        return max_width;
    }
    

    }

    which I took here - Why is wrap content in multiple line TextView filling parent?

提交回复
热议问题