在 Android Studio 中防止文本换行

Prevent text from wrapping into a new line in Android Studio

我正在尝试在 Android Studio 中将文本直方图显示到 TextView 中,但我不希望它打断字符行并将它们分成两行,因为它显然会破坏直方图。当我有越来越多的行时,我将文本设置为调整自身大小以适应文本框,但我想专门将大小缩放到最长的行,这样它们都在一行上。

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" />

这是我在 textview XML 中用来缩放字体大小的内容。

创建约束布局作为文本视图的父级。设置您的文本视图宽度以匹配约束。一切顺利。

无论出于何种原因,您也必须设置 android:maxLines 才能使自动调整大小正常工作(最好使用 app:autoSize* 而不是 android:autoSize* 来支持API 个级别 < 26 或者如果您使用 AppCompat 个组件)。

有很多关于正确执行此操作的细节 - 除了使用 maxLines 之外的一些关键要点是:不要使用 android:singleLine,并且不要使用 wrap_content 宽度或高度。

演示使用

<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"/>

如果最大行数动态变化,你可以在代码中设置它,像这样

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
}