【问题标题】:Distribute TextViews in LinearLayout based on content根据内容在 LinearLayout 中分配 TextView
【发布时间】:2017-07-02 10:31:59
【问题描述】:

如标题中所述,我试图在 LinearLayout 中让 2 个 TextView 彼此相邻。例如,两个文本视图都包含 10 个单词。在这种情况下,我希望它们的宽度为 50%。但是,当第一个 TextView 有 10 个单词,而另一个有 1 个单词时,我希望第一个 TextView 更宽一些(大约 90% 左右)。我该怎么做?

注意:我确实尝试过搜索,但我发现的唯一内容是如何在 TextView 中调整 字体

我添加了一些 TextView 外观的视觉效果(不要介意 Android Studio 随机悬停边框)。

还有我当前的代码,如果你想帮忙的话:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/title"
        android:text="My title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:textSize="16sp"
        android:maxLines="1"
        android:ellipsize="end"/>

    <TextView
        android:id="@+id/my_other_title"
        android:text="My other title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:textAlignment="textEnd"
        android:maxLines="1"
        android:ellipsize="end"/>

</LinearLayout>

注意:我宁愿只使用 xml,但如果只能以编程方式实现,那么就可以了

【问题讨论】:

  • 如果你说你想改变 TextView 的权重,这取决于它有多少个单词,你必须在代码中使用条件动态地做到这一点。 XML 只能以静态方式完成。

标签: android xml android-layout android-linearlayout textview


【解决方案1】:

为此,您必须使用文本长度计算两个 TextView 的估计权重。 其他标题的长度将作为标题的权重,标题的长度将作为标题的权重另一个标题

LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
titleParams.weight = myOtherTitle.getText().length();

LinearLayout.LayoutParams myOtherTitleParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
myOtherTitleParams.weight = title.getText().length();

title.setLayoutParams(titleParams);
myOtherTitle.setLayoutParams(myOtherTitleParams);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多