根据内容在LinearLayout中分发TextViews

时间:2017-07-02 10:31:59

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

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

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

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

enter image description here

我目前的代码,如果你想提供帮助:

<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,但如果只能以编程方式使用,那么

1 个答案:

答案 0 :(得分:0)

为了做到这一点,你必须使用文本的长度来计算两个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);