2017-10-29 28 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