Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2920
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  旧时难觅i
    2020-11-21 06:04

    Actually a solution is in Google's DialogTitle class... though it's not as effective as the accepted one, it's a lot simpler and is easy to adapt.

    public class SingleLineTextView extends TextView {
    
      public SingleLineTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setSingleLine();
        setEllipsize(TruncateAt.END);
      }
    
      public SingleLineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setSingleLine();
        setEllipsize(TruncateAt.END);
      }
    
      public SingleLineTextView(Context context) {
        super(context);
        setSingleLine();
        setEllipsize(TruncateAt.END);
      }
    
      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
        final Layout layout = getLayout();
        if (layout != null) {
          final int lineCount = layout.getLineCount();
          if (lineCount > 0) {
            final int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
            if (ellipsisCount > 0) {
    
              final float textSize = getTextSize();
    
              // textSize is already expressed in pixels
              setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));
    
              super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
          }
        }
      }
    
    }
    

提交回复
热议问题