Android weightsum未按预期工作

Android weightsum未按预期工作,android,android-linearlayout,android-layout-weight,Android,Android Linearlayout,Android Layout Weight,我有一个水平线性布局,宽度=match_parent,权重总和=5。 如果我插入5个垂直线性布局,每个宽度为0,权重为1,所有内容看起来都与预期的一样,每个布局的宽度都相同。 如果我只加两个垂直的,每个宽度=0,重量=1,它们会占用更多的空间。我希望他们也能占据1/5的空间 也许这是正确的行为,他们占用了更多的空间,我理解重量/重量和的概念是错误的 谢谢你的帮助 编辑: 我尝试添加一些代码 LinearLayout linear=null; LinearLayout.LayoutParams

我有一个水平线性布局,宽度=match_parent,权重总和=5。 如果我插入5个垂直线性布局,每个宽度为0,权重为1,所有内容看起来都与预期的一样,每个布局的宽度都相同。 如果我只加两个垂直的,每个宽度=0,重量=1,它们会占用更多的空间。我希望他们也能占据1/5的空间

也许这是正确的行为,他们占用了更多的空间,我理解重量/重量和的概念是错误的

谢谢你的帮助

编辑: 我尝试添加一些代码

LinearLayout linear=null;
LinearLayout.LayoutParams LayoutParams=新建
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_父项,
LinearLayout.LayoutParams.WRAP_内容);
线性=新的线性布局(getApplicationContext());
线性。设置方向(线性布局。水平);
线性。setLayoutParams(layoutParams);
线性。设置填充(15,0,15,10);
线性。设置权重和(浮点。值(模));
//在我的例子中是模5
LinearLayout linear2=新的LinearLayout(getApplicationContext());
LinearLayout.LayoutParams lp1=新的LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_内容,1f);
if(计数%modulo!=模-1){
lp1.setMargins(0,0,15,0);
}否则{
lp1.setMargins(0,0,0,0);
}
linear2.setLayoutParams(lp1);
linear2.设置方向(LinearLayout.垂直)试试这个

    <?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="5">
<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_light"
    android:layout_weight="1"/>

<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright"
    android:layout_weight="1"/>
</LinearLayout>



平均分配重量。

如果逻辑解决方案不起作用,则用

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_weight="3"/> <!-- or whatever the rest is -->

注意:
Space
小部件在这种情况下不起作用。

您也可以发布一个屏幕截图吗?对于布局权重属性,这是不可能的。使用布局权重时,视图都相等并填充整个位置。但我将weightsum设置为5,布局权重设置为1,这样它们都应该占据空间的1/5?当初始化布局以填充父视图时,weightsum工作正常。我可以在你的代码中看到,你已经用高度包裹内容初始化了你的线性布局,但是我用宽度作为权重,为什么高度会影响结果?我用这个替换了所有的AppContext。空间的东西也不起作用,总是一样的结果:(嗯……首先尝试高度
1
(这是第二个布局参数),如果不起作用,请尝试
查看
而不是
空间
,如果不起作用,请尝试将两者结合起来,如果不起作用……无论如何,请让我知道。因此,如果我使用视图,但使用权重为3的空间除外。我真的不喜欢这种“变通方法”但至少它符合我的要求。非常感谢您的帮助。如果您编辑您的答案,我会将其标记为“高度中使用的权重总和正确吗?”?
<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_weight="3"/> <!-- or whatever the rest is -->
View space = new View(this); // NEVER CREATE VIEWS WITH APP CONTEXT!
LinearLayout.LayoutParams spaceParams = new LinearLayout.LayoutParams(0, 0, 3f);
linear.addView(space, spaceParams);