2017-10-29 84 views
0

我有一個LinearLayout(水平)與幾個子TextViews裏面。我爲LinearLayout和所有TextView設置了固定的layout_width。當孩子的總寬度超過佈局的寬度時,它會自動縮小孩子,使他們變窄,這不是我想要的。我希望佈局剪輯兒童內容並保持其寬度。 我該如何做到這一點?如何讓Android LinearLayout剪輯其子內容?

例如:假設我的LinearLayout寬度爲200dp,每個寬度爲60dp有4個TextView。我希望它顯示前三個TextViews和第四個的1/3(60 + 60 + 60 + 20 = 200)

謝謝。

+0

粘貼您的代碼 –

回答

0
  • 使用android:weightSumLinearLayout

  • 而且使用android:layout_width="0dp"android:layout_weight="1"TextView

試試這個。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:orientation="horizontal" 
      android:weightSum="10"> 

<TextView 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="3" 
    android:text="hello"/> 

<TextView 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="3" 
    android:text="hello"/> 

<TextView 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="3" 
    android:text="hello"/> 

<TextView 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" 
    android:text="hello"/> 

</LinearLayout> 

此外

您可以TextView改變android:layout_width="match_parent"android:layout_width="wrap_content"

編輯

你可以在Java代碼中使用。

您可以自己改變寬度或重量。

private LinearLayout mLinearLayout; 
private int viewsCount = 4; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mLinearLayout = (LinearLayout) findViewById(R.id.linearlayout); 
    for (int i = 0; i < viewsCount; i++) { 
     TextView textView = new TextView(this); 
     if(i == viewsCount-1){ 
      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1); 
     } else { 
      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 3); 
     } 
     mLinearLayout.addView(textView); 
    } 
} 
+0

您的第一個解決方案將顯示前三個TextView並隱藏後續的。它仍然將LinearLayout空間平均分配在前三個之間,這不是我的情況。我希望LinearLayout將我的TextView保持在指定的寬度,儘可能多地顯示內容,剪切剩下的內容。例如。假設我的LinearLayout寬度爲200dp,並且每個60dp有4個TextView。我希望它顯示前三個TextViews和四分之一的三分之一。 p.s.我可以用RelativeLayout和ConstraintLayout來做到這一點,但是想要使用LinearLayout。 – ScottD

+0

您可以爲'3,3,3,1'設置權重。 – KeLiuyue

+0

如果你不想平均最後的'textview'。你可以使用''。 – KeLiuyue