2013-08-20 31 views
1

使用案例:對齊視圖動態地重 - 的Android

我有一個水平視圖H,其包含5個按鈕(A,B,C,d & E);所有在H中佔用相等的空間。現在,根據特定的業務邏輯,這些按鈕中的每一個都可能可見或不可見。如果一個按鈕不可見,其餘的按鈕應該平等對齊。

現在的問題是,如果我給每個這些按鈕特定的權重,那麼我必須編寫2^5 if-else case來爲按鈕分配單獨的權重。在Android中沒有一種方式,所有這些按鈕使他們自己平等地佔用空間。準確地說,這個想法是隻寫5個例子,讓我可以看到或不可見的按鈕,並且休息視圖自行對齊。我不能使用換行內容,因爲這些按鈕包含不同長度的文本,我希望按鈕佔用相同的空間而不是文本。

有沒有辦法做到這一點?我將非常感謝這裏的任何幫助。

回答

3

指定所有按鈕的權重相等(例如1),但不要將權重總和分配給容器。現在,當您需要隱藏按鈕時,將其可見性設置爲GONE,其他按鈕的大小將相同,以佔用可用空間。

+0

非常感謝!我正在尋找這樣的解決方案:) –

0
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/white" 
    android:orientation="vertical" > 

    <Button 
     android:layout_width="fill_parent" 
     android:layout_weight="1" /> 

    <Button 
     android:layout_width="fill_parent" 
     android:layout_weight="1" /> 

    <Button 
     android:layout_width="fill_parent" 
     android:layout_weight="1" 
     android:visibility="gone" /> 

</LinearLayout> 

現在,如果您設置可見的第三個按鈕,其他兩個buttos將調整大小以顯示屏幕上的3個按鈕。水平佈局中的相同視圖:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/white" 
    android:orientation="horizontal" > 

    <Button 
     android:layout_height="fill_parent" 
     android:layout_weight="1" /> 

    <Button 
     android:layout_height="fill_parent" 
     android:layout_weight="1" /> 

    <Button 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:visibility="gone" /> 

</LinearLayout> 
+0

謝謝您的及時回覆! –