根据内容在LinearLayout中分配TextViews

问题描述:

正如标题所述,我想在LinearLayout中的eachother旁边放置2个TextViews。例如,两个文本视图均包含10个单词。在这种情况下,我希望它们的宽度为50%。但是,当第一个TextView有10个字,另一个有1个字时,我希望第一个TextView更宽(约90%左右)。我该怎么做?根据内容在LinearLayout中分配TextViews

注意:我确实尝试搜索,但我发现的唯一的东西是如何在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

如果你说你想改变TextView的权重取决于有多少单词,你必须在代码中使用条件动态地执行它。 XML只能以静态方式进行。 – anton86993

为了做到这一点,你必须使用文本的长度来计算两个TextViews的估计权重。所述其他标题的长度将被用作权重为标题,并且标题的长度将被用于其他标题重量。

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);