首页 > 解决方案 > TextView 包装在 GridLayout 中无法正常工作

问题描述

我在一个轻量级应用程序中有以下布局(请不要建议添加新的依赖项,比如Appcompator ConstraintLayout,它们都会给 APK 添加超过 1MB 的空间):

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:columnCount="2">

  <TextView
    android:layout_gravity="center"
    android:layout_margin="8dp"
    android:text="Left text. word1 word2 word3" />

  <TextView
    android:layout_gravity="center"
    android:layout_margin="8dp"
    android:text="Right text. word1 word2 word3 word4 word5 word6 word7 word8 word9 word10" />
</GridLayout>

不幸的是,结果不正确:第二个TextView是试图变得太大,导致文本被截断: 截屏

看起来它TextView正在扩展,直到它达到其父级的宽度,然后才开始包装。但它应该只会增长,直到达到其父级分配的宽度。这是一个明显的错误TextView,还是我滥用了它?知道如何解决这个问题吗?

标签: androidandroid-layout

解决方案


可以这样使用FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/GridLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="2"
    >

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_columnWeight="1"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="@string/lorem_ipsum"
            />

    </FrameLayout>

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_columnWeight="1"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="@string/short_string"
            />

    </FrameLayout>

</GridLayout>

结果:

在此处输入图像描述


推荐阅读