Jadon Latta
Jadon Latta

Reputation: 197

Prevent text from wrapping into a new line in Android Studio

I am trying to display a textual histogram into a TextView in Android Studio but I don't want it to break the line of characters and separate them onto two lines, because it obviously ruins the histogram. I have the text set to resize itself in order to fit into the text box when I have more and more lines, but I want to make the size scale to the longest line specifically, that way they are all on a single line.

Here is what the histogram is showing, rather than adjusting the line size

<TextView
        android:id="@+id/histogramTextbox"
        android:layout_width="0dp"
        android:layout_height="453dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:autoSizeMaxTextSize="80sp"
        android:autoSizeMinTextSize="12sp"
        android:autoSizeStepGranularity="2sp"
        android:autoSizeTextType="uniform"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/totalRollsText" />

Here is what I have in my textview XML in order to scale the font size.

Upvotes: 1

Views: 1868

Answers (2)

Tyler V
Tyler V

Reputation: 10910

For whatever reason, you have to set android:maxLines too in order to get the autosizing to work properly (and it's a good idea to use app:autoSize* instead of android:autoSize* to support API levels < 26 or if you are using AppCompat components).

There are a lot of details about getting this right here - some key takeaways in addition to using maxLines are: do not use android:singleLine, and do not use wrap_content for either width or height.

Demo Use

<TextView
    android:id="@+id/histogram_text"
    android:layout_width="0dp"
    android:layout_height="400dp"
    android:layout_marginStart="36dp"
    android:layout_marginEnd="36dp"
    android:maxLines="5"
    app:autoSizeMaxTextSize="20sp"
    app:autoSizeMinTextSize="4dp"
    app:autoSizeStepGranularity="1sp"
    app:autoSizeTextType="uniform"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/get_text"/>

If the max lines changes dynamically, you can set it in code instead, like this

private fun expandHistogram() {
    var demoHist = "(01): #\n"
    demoHist += "(02): ##\n"
    demoHist += "(03): ##############\n"
    demoHist += "(04): " + "#".repeat(h) + "\n"
    demoHist += "(05): ##############\n"
    binding.histogramText.text = demoHist
    binding.histogramText.maxLines = 5
    h += 5
}

Auto-sizing demo

Upvotes: 1

Joseph .A.
Joseph .A.

Reputation: 75

Create constraintlayout as parent of a textview. Set your textview width to match constraint. You are good to go.

Upvotes: 0

Related Questions