【发布时间】:2018-12-11 18:30:47
【问题描述】:
如果 TextView 不适合当前行,我想自动将其移至下一行。例如,我在一个布局中有 20 个 TextView,并希望在其中设置客户名称。有些客户名称很长,有些很短。根据该行中的可用空间,应该显示一个 TextView。如果没有空间,那么它应该自动移动到该布局中的下一行。
谁能帮我解决这个问题?
【问题讨论】:
标签: java android android-studio-3.0
如果 TextView 不适合当前行,我想自动将其移至下一行。例如,我在一个布局中有 20 个 TextView,并希望在其中设置客户名称。有些客户名称很长,有些很短。根据该行中的可用空间,应该显示一个 TextView。如果没有空间,那么它应该自动移动到该布局中的下一行。
谁能帮我解决这个问题?
【问题讨论】:
标签: java android android-studio-3.0
标准的 Android 框架中没有任何东西可以让您这样做,但是 Google 提供了一个非常好的外部库,名为 FlexboxLayout,可以为您做到这一点。
您将使用 FlexboxLayout 作为所有 TextViews 的父级,而不是例如LinearLayout,它会为你包装它们。
<com.google.android.flexbox.FlexboxLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:flexWrap="wrap">
<!-- add your 20 textviews here -->
</com.google.android.flexbox.FlexboxLayout>
请注意,指定app:flexWrap="wrap" 很重要,因为默认情况下不进行换行。我不知道为什么会这样,因为使用这个库的全部意义在于进行包装,但是嘿。
【讨论】:
听起来您正在尝试将某些文本视图芯片化。您将需要某种布局管理器来测量视图并确定如何显示它们。在 Github 上查看此内容或与 ContactChips 相关的任何内容都可能有用。 Chips Layout Manager
【讨论】:
使用高度作为 wrap_content 和宽度作为 match_parent 创建线性布局,然后在其中创建 Textview 并将其高度作为 wrap_content 以便当您的内容增加时它会自动扩展。就这么简单。您可以查看以下示例。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:singleLine="false"
android:textColor="@color/black"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
【讨论】: