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

时间:2018-03-13 22:13:46

标签: android android-layout android-constraintlayout autosize

考虑这种布局:

<?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>

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

autosized TextView

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

non-autosized TextView

有没有办法充分发挥两个世界的优势---让文本根据已知高度自动调整大小,然后根据自动调整文本的宽度设置宽度?

3 个答案:

答案 0 :(得分:2)

Google的developer documentation特别建议不要将wrap_content与自动调整的TextViews一起使用:

  

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

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

如果您使用match_parent0dp的宽度确实无法在TextView上获得额外的水平空间,则可以尝试以编程方式设置textview宽度布局参数,具体取决于使用创建布局后TextPaint

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);
    }
});

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

答案 1 :(得分:0)

尝试将0dp(等于MATCH_CONSTRAINT)用于android:layout_width的{​​{1}}属性。

答案 2 :(得分:-3)

你可以试试这个

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