2012-05-20 95 views
1

在我的应用程序中,我有2个线性布局:一个在顶部,一个在底部。固定比例的屏幕布局

我想那不管是在这些布局里面,顶层的布局占据了屏幕高度的60%和底层布局的40%。 这里是我的XML代码:

<?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="vertical" 
    android:layout_weight="1.0" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.6" 
     android:orientation="vertical" 
     android:id="@+id/layout_top"> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:layout_weight="0.4" 
     android:id="@+id/layout_bottom"> 
    </LinearLayout> 

</LinearLayout> 

当这些布局都是空的,没有任何问题,他们有良好的比例。

问题是,如果我把一个小的列表视图的顶部布局为例如,那么布局将采用列表视图的大小,并不会保留60/40%的比例。

即使我的列表视图很小(例如只有3个项目),布局保留了60%,因此在我的列表视图下放置了一些空白空间。

我试过把android:layout_height改成match_parent但是它没有改变任何东西。

谢谢。

+0

你的布局似乎很好。你能否展示你如何在顶层布局中添加一个小的列表视图。 – rizzz86

回答

6

尝试使用此布局工作对我来说

<?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="vertical" 
    android:layout_weight="1.0" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:layout_weight="6" 
     android:orientation="vertical" 
     android:id="@+id/layout_top" 
     android:background="#FF0000"> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:orientation="vertical" 
     android:layout_weight="4" 
     android:id="@+id/layout_bottom" 
     android:background="#FF00FF"> 
    </LinearLayout> 

</LinearLayout> 

的诀窍是在风景模式下,你可以用它来建立一个layout_height="0dip"而不是在纵向模式下WRAP_CONTENT和layout_with="0dip"代替WRAP_CONTENT的布局土地文件夹。

+0

它的工作原理,非常感谢:)! – Jecimi

1

layout_weight在layout的视图中指定额外的空间。你应该尝试先测量你的屏幕,如:

Display display = ((WindowManager) 
    getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
int width = display.getHeight(); 

,然后做一些计算一样宽* 0.6和0.4,这样一来你的布局将始终有60 40的比例。

希望这有助于

0

尝试layout_height = 0dp在两个孩子LinearLayouts。它的发生是因为您有wrap_content这可能会覆盖layout_weight效应。

0

只需在您的父母布局,android:weightSum="1.0"

这通过设置权重和父布局和孩子们布局的权重更换android:layout_weight="1.0"。孩子的体重应该等于父母的体重总和。看看这个http://blog.stylingandroid.com/archives/312