自动调整 Android TextView 大小时如何“wrap_content”?

Jos*_*sen 8 android autosize android-layout android-constraintlayout

考虑这个布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:autoSizeTextType="uniform"
        android:gravity="center"
        android:maxLines="1"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_max="50dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

由于height_max限制,这会导致 TextView,其中文本填充垂直空间,但 TextView 内部有很多水平填充:

自动调整文本视图

我想要的是设置该 TextView 的宽度,使其与自动调整大小的文本内容的宽度相匹配。但是当我android:layout_width="wrap_content"根据非自动调整大小的文本内容设置宽度时:

非自动调整的 TextView

有什么方法可以两全其美——让文本根据已知高度自动调整大小,然后根据自动调整大小文本的宽度设置宽度?

rjr*_*pps 7

Google 的开发人员文档特别建议不要使用wrap_content自动调整大小的 TextViews:

注意:如果您在 XML 文件中设置 autosizing,则不建议为 TextView 的 layout_width 或 layout_height 属性使用值“wrap_content”。它可能会产生意想不到的结果。

如果您只是希望文本的高度为 50dp 而不是 50sp,您可以将 textSize 设置为 50dp。但我怀疑您的目标是拥有一个 textView,它会根据布局约束自动缩小文本的大小,而该解决方案无法完成这项工作。

如果您确实无法通过使用match_parent或的宽度在 TextView 上获得额外的水平空间0dp,则可以尝试基于在TextPaint创建布局后使用 a 测量文本以编程方式设置 textview 宽度布局参数:

textView.post(new Runnable() {
    @Override
    public void run() {
        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(textView.getTextSize());

        float width = textPaint.measureText(textView.getText().toString());

        ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
        layoutParams.width = (int)width;
        textView.setLayoutParams(layoutParams);
    }
});
Run Code Online (Sandbox Code Playgroud)

请记住,如果您走这条路线,您可能需要为其添加一些左右填充。TextViews 有一种内部填充,即使您将它们的填充设置为零 - 但是当直接设置宽度参数时,它会被覆盖。


小智 -4

你可以试试这个

<TextView
android:id="@+id/vName"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Groupa"
app:autoSizeMinTextSize="12sp"
app:autoSizeMaxTextSize="20sp"
app:autoSizeTextType="uniform"
/>
Run Code Online (Sandbox Code Playgroud)

  • 提供的链接似乎没有解决当前的问题 (3认同)