1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.android.setupdesign.view; 18 19 import static java.lang.Math.max; 20 21 import android.content.Context; 22 import androidx.appcompat.widget.AppCompatTextView; 23 import android.text.Layout; 24 import android.util.AttributeSet; 25 import android.view.View; 26 import androidx.annotation.VisibleForTesting; 27 28 /** 29 * A TextView that, when its width is wrap_content, will repeatedly measure until we get a width 30 * that actually wraps its text label. 31 */ 32 public class WrapTextView extends AppCompatTextView { 33 WrapTextView(Context context)34 public WrapTextView(Context context) { 35 super(context); 36 } 37 WrapTextView(Context context, AttributeSet attrs)38 public WrapTextView(Context context, AttributeSet attrs) { 39 super(context, attrs); 40 } 41 WrapTextView(Context context, AttributeSet attrs, int defStyleAttr)42 public WrapTextView(Context context, AttributeSet attrs, int defStyleAttr) { 43 super(context, attrs, defStyleAttr); 44 } 45 46 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)47 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 48 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 49 int newWidthSpec = wrapMeasure(widthMeasureSpec); 50 if (newWidthSpec != widthMeasureSpec) { 51 super.onMeasure(newWidthSpec, heightMeasureSpec); 52 } 53 } 54 55 @VisibleForTesting wrapMeasure(int widthMeasureSpec)56 int wrapMeasure(int widthMeasureSpec) { 57 if (View.MeasureSpec.getMode(widthMeasureSpec) == View.MeasureSpec.AT_MOST) { 58 final Layout layout = getLayout(); 59 final int lineCount = layout.getLineCount(); 60 if (lineCount > 1) { 61 float maxLineWidth = 0; 62 for (int i = 0; i < lineCount; i++) { 63 // Find the longest line width 64 maxLineWidth = max(maxLineWidth, layout.getLineWidth(i)); 65 } 66 final int newTotalWidth = 67 (int) Math.ceil(maxLineWidth) + getTotalPaddingLeft() + getTotalPaddingRight(); 68 if (newTotalWidth < getMeasuredWidth()) { 69 // Re-measure with the longest line length if it has changed. 70 return View.MeasureSpec.makeMeasureSpec(newTotalWidth, View.MeasureSpec.AT_MOST); 71 } 72 } 73 } 74 return widthMeasureSpec; 75 } 76 } 77