Why does TextView have end padding when multi line?

前端 未结 4 834
执念已碎
执念已碎 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:07

    I found the selected answer to be helpful, although it didn't quite account for padding. I combined the selected answer with this post's answer to come up with a view that works with padding. FYI, the other post's answer had a flaw where the view would sometimes get cut-off at the end by a few pixels.

    public class TightTextView extends TextView {
      public TightTextView(Context context) {
        super(context);
      }
    
      public TightTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      public TightTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
      }
    
      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        int specModeW = MeasureSpec.getMode(widthMeasureSpec);
        if (specModeW != MeasureSpec.EXACTLY) {
          Layout layout = getLayout();
          if (layout != null) {
            int w = (int) Math.ceil(getMaxLineWidth(layout)) + getCompoundPaddingLeft() + getCompoundPaddingRight();
            if (w < getMeasuredWidth()) {
              super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST),
              heightMeasureSpec);
            }
          }
        }
      }
    
      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;
      }
    }
    

提交回复
热议问题