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

后端 未结 2 799
慢半拍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 16:20

    You'll need to measure the width of the text in TextView programatically, like so:

    Rect bounds = new Rect();
    textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);
    

    Now, you can place a colored rectangle behind the TextView, and set its width programatically after measuring the text (I'm using FrameLayout to put the Views one on top of the other, but you can use RelativeLayout as well):

    XML:

    
    
        
    
        
    
    

    Code:

    Rect bounds = new Rect();
    textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);
    View bg = findViewById(R.id.background);
    gb.getLayoutParams().width = bounds.width();
    

    Code is untested, but I'm sure you get the point.

    UPDATE

    It may be possible to do this without using a second background view, by setting the TextView width to match bounds.width(), but this trigger a change in how the text breaks, so need to be careful not to cause an infinite loop.

提交回复
热议问题