繁体   English   中英

如果文本被迫在文本视图中换行,如何在给定字符处换行? (安卓)

[英]How to break lines at a given character if the text is forced to wrap in your textview? (android)

所以我将 textview 的高度设置为包装内容。 它以“CHI 99 CHA 88”格式显示体育比分。 我让 textview 匹配父级的宽度。 我还将分数文本设置为以“sp”为单位的特定文本大小。

因此,在较小的手机上,如果乐谱中有更多字符,或者如果更改字体大小(辅助功能设置),则文本可能需要换行成 2 行。 但是,我想要一种方法来控制它决定将文本换行并换行的位置(在字符串中)。 它以“CHI 99\\nCHA 88”的形式看起来最好。 但我更喜欢文本在同一行上,除非它被屏幕大小、字符数或可访问性设置强制换行,所以我不想从一开始就用“\\n”硬编码。

所以基本上,如果有必要将文本换行到新行上,是否有办法控制文本决定在哪个字符处创建新行。

感谢您的任何回复!

您可以通过使用 autosize 避免换行并将 maxLines 设置为 1,如下所示:

<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    android:autoSizeMinTextSize="12sp"
    android:autoSizeMaxTextSize="100sp"
    android:autoSizeStepGranularity="2sp"
    android:maxLines="1"  />

来源: https : //developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview

您可以根据屏幕宽度计算一行中的字符,然后添加新行字符。

可以使用带有两个 TextViews 的Flow小部件来控制它,而不是以编程方式计算显示大小/字符等。

一个示例布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="150dp"
    android:layout_height="match_parent">

    <androidx.constraintlayout.helper.widget.Flow
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="text1,text2"
        app:flow_horizontalBias="0"
        app:flow_horizontalGap="5dp"
        app:flow_horizontalStyle="packed"
        app:flow_wrapMode="chain"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CHI 99" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CHA 88" />
</androidx.constraintlayout.widget.ConstraintLayout>

通常,使用默认大小,它看起来像这样:

布局

如果视图不能水平放置,则第二个 TextView 移动到下一行:

布局

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM