2012-04-22 68 views
4

我有一個複雜的佈局情況,其中一個水平的LinearLayout擁有另外兩個LinearLayout s。這些佈局的內容是動態的,可以是任何類型的視圖,並且是在運行時從不同的獨立源生成的。LinearLayout空間分配

只要有足夠的空間,我想要顯示它們兩個,並將其限制爲每個空間的50%。所以我希望那些孩子LinearLayout s有layout_width="wrap_content"時有足夠的空間,並且layout_weight="0.5"時沒有。這意味着空間分佈可以是10-90,25-75,60-40;當沒有足夠的空間來顯示兩個視圖的全部內容時,它只會是50-50。到目前爲止,我還沒有找到一種方法來從XML中做到這一點,所以我從代碼中做到了這一點。我的問題是我可以使用XML屬性來實現我想要的嗎?另一種佈局能做到嗎?

這是我目前的佈局XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical" 
    android:orientation="horizontal" 
    android:padding="2dp" > 

    <LinearLayout 
     android:id="@+id/title_frame" 
     android:layout_width="wrap_content" 
     android:layout_height="48dp"/> 

    <LinearLayout 
     android:id="@+id/options_frame" 
     android:layout_width="wrap_content" 
     android:layout_height="48dp"/> 

</LinearLayout> 
+0

你可以添加你的xml文件嗎 – 2012-04-22 03:42:13

回答

1

看起來這不能使用XML屬性來實現。

+0

通過什麼可以實現...? :)你知道這可以編碼嗎? – Zordid 2014-04-04 09:42:50

0

變化layout_width = 「WRAP_CONTENT」 到layout_width = 「FILL_PARENT」 爲你使用重量概念。

+0

'layout_weight'指示'LinearLayout'中多餘的額外空間將被分配給關聯的視圖。如果我要設置'layout_width =「fill_parent」',則不會有任何額外的空間可供分配。 – 2012-04-22 03:54:59

+0

根據我的說法,我們必須設置填充父項,然後在您的案例中至少分配權重。嘗試一次可以解決你的問題? – 2012-04-22 03:56:52

+0

你試過了嗎? – 2012-04-22 04:39:35

2

試試這個。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical" 
    android:orientation="horizontal" 
    android:padding="2dp" > 

    <LinearLayout 
     android:id="@+id/title_frame" 
     android:layout_width="wrap_content" 
     android:layout_height="48dp" android:layout_weight="1"> 

    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/options_frame" 
     android:layout_width="wrap_content" 
     android:layout_height="48dp" android:layout_weight="1"> 

    </LinearLayout> 

</LinearLayout> 

我用textviews試過了,這應該根據ure要求工作。

+0

這似乎是個竅門!但它是如何工作的? 「負面的」額外空間是否平均分配給孩子? – 2012-04-22 14:40:05

+0

重量是一個棘手的概念,我也試圖去掌握。在這種情況下,會發生什麼情況是兩個佈局的權重相同,同時它們也被製作爲wrap_content。如果一個項目中沒有項目,另一個項目中有多個項目,則wrap_content會嘗試封裝空白布局,並以空白結束,導致另一個項目展開並填充其位置。如果你做了fill_parent,即使一個佈局是空的,2個佈局也會佔用相同的空間。這是我基於實驗的理解。我計劃檢查執行一旦我有時間:) – Shubhayu 2012-04-22 17:40:37

+0

不幸的是,這並不完全按要求工作。當兩個孩子的寬度之和大於可用空間並且一個比另一個大得多時,即使其尺寸小於可用空間的一半,較短的一個也不會完全顯示。 – 2012-04-23 20:16:40