Search code examples
androidtextview

Android: Find and set the length of a textview based on a string length


I have a textview which can take values "select all" or "deselect all". I want to set the width to be the length of the longest of these two strings. (As this can change with language). How can i set this? The text is a string resource. My layout is

<?xml version="1.0" encoding="utf-8"?>

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"

app:layout_constraintHeight_min="32dp">



<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/name_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:paddingStart="16dp"
    android:paddingEnd="16dp"
    android:textColor="@color/blackColor"
    android:textSize="16sp"
    android:textStyle="normal"
    android:inputType="textFilter|textMultiLine"
    app:fontFamily="@font/lato_semibold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/select_text"
    app:layout_constraintHorizontal_bias="0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="Google Nest" />

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/select_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:paddingEnd="16dp"
    android:textSize="12sp"
    android:text="@string/selectAll"

    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="Select All" />


Solution

  • You could use the TextView's Paint object to measure the width of each text and then apply the width manually like so:

    TextView textView = findViewById(R.id.my_text_view);
    String selectText = getString(R.string.select_all);
    String deselectText = getString(R.string.deselect_all);
    float selectWidth = textView.getPaint().measureText(selectText);
    float deselectWidth = textView.getPaint().measureText(deselectText);
    ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
    layoutParams.width = (int) Math.max(selectWidth, deselectWidth);
    textView.setLayoutParams(layoutParams);
    

    Be aware that measuring the width in this way will not account for wrapping text. So this might not work out if some translations turn out very long.