【问题标题】:Android : How to set TextView text size dynamically so that text do not wrap to next lineAndroid:如何动态设置 TextView 文本大小,以便文本不会换行到下一行
【发布时间】:2019-01-29 15:15:26
【问题描述】:

我有这段代码。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.8"
    android:orientation="vertical"
    android:id="@+id/textLayout"
    android:background="@drawable/vdaybg"
    android:gravity="center"
    android:layout_gravity="center">
    <TextView
        android:id="@+id/detail_text"
        android:text="hello"
        android:background="#55000000"
        android:lineSpacingExtra="5dp"
        android:textSize="30dp"
        android:textColor="@android:color/white"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </TextView>
</LinearLayout>

我正在从 Activity 动态设置文本

detailText.setText(msg);
detailText.setTypeface(Utils.typeFaceBold);

现在由于我设置了多行文本,因此较大的行换行到下一行。 我想阻止这种情况。 当线条即将变形时,我想减小字体大小。

目前我已经找到了执行此操作的这段代码

public void correctWidth(TextView textView, int desiredWidth) {
        Paint paint = new Paint();
        Rect bounds = new Rect();

        paint.setTypeface(textView.getTypeface());
        float textSize = textView.getTextSize();
        paint.setTextSize(textSize);
        String text = textView.getText().toString();
        paint.getTextBounds(text, 0, text.length(), bounds);

        while (bounds.width() > desiredWidth)
        {
            textSize--;
            paint.setTextSize(textSize);
            paint.getTextBounds(text, 0, text.length(), bounds);
        }

        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    }

但是在desiredWidth 中传递什么?它会起作用吗?

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以使用 Autosizing TextViews 来定义多个文本大小。

    <resources>
      <array name="autosize_text_sizes">
        <item>10sp</item>
        <item>12sp</item>
        <item>20sp</item>
        <item>40sp</item>
        <item>100sp</item>
      </array>
    </resources>
    
    <?xml version="1.0" encoding="utf-8"?>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:autoSizeTextType="uniform"
        android:autoSizePresetSizes="@array/autosize_text_sizes" />
    

    这是来自 Android 开发者网站的Autosizing TextViews 官方文档。

    【讨论】:

    • 已经尝试过了,但这并不能防止换行。它将适合高度
    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    相关资源
    最近更新 更多