LinearLayout内的TextView拉伸LinearLayout和fill_parent修复导致重量翻转

时间:2010-08-21 02:47:41

标签: android textview android-linearlayout android-xml android-layout-weight

如果我有2个LinearLayouts拆分%50 /%50一切都很好。权重为1和1.只要在顶部LinearLayout中添加TextView,它就会延伸该布局。我使用wrap_content作为文档说我应该权衡。

如您所见,红色和绿色应均匀分割,灰色背景上的文字应位于红色框内。这是代码:

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#ff0000"
>
 <TextView
 android:text="@string/hello"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:background="#cccccc"
 android:textColor="#000000"/>      
</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ff00"
>
</LinearLayout>    

现在,如果我按如下方式切换到“填充父级”,它实际上可以工作,但它会产生另一个问题。这是代码(到目前为止很好):

 <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="#ff0000"
    >
     <TextView
     android:text="@string/hello"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:background="#cccccc"
     android:textColor="#000000"/>      
    </LinearLayout>

 <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="#00ff00"
    >
    </LinearLayout>

所以看看上面我们被迫使用fill_parent我们会认为我们修复了问题,但是如果我们使用fill_parent就会出现问题(我拿出TextView只是为了显示问题,TextView不会让问题彻底消失):

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

 <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="3"
    android:background="#ff0000"
    >
    </LinearLayout>


 <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="2"
    android:background="#00ff00"
    >
    </LinearLayout> 
</LinearLayout>

正如你所看到的,我指定了权重3(顶部红色)和2(底部绿色),但实际发生的是它们被翻转:红色变为2而底部变为3.只需测量像素也可以看到。

以下是3个代码的结果:

为了清楚起见,每次布局都包含在此内部(顶部布局):

android:layout_width="fill_parent"
android:layout_height="fill_parent"

使用XML version="1.0" encoding="utf-8"和正确的命名空间。

2 个答案:

答案 0 :(得分:1)

组合子视图权重最多应为1 .....例如。 .3,.3,.4 = 1,或100%

答案 1 :(得分:0)

尝试将子视图添加到底部布局。