-1

正如標題所述,我想在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

回答

0

爲了做到這一點,你必須使用文本的長度來計算兩個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);