layout_below 和 LinearLayout 的权重和以编程方式

layout_below and weightsum of LinearLayout Programmatically

我正在以编程方式在 RelativeLayout 中创建 LinearLayout。我想要做的是在 LinearLayout 中分配 weigtsum 并且还想设置 layout_above 属性。问题是 weightSumLinearLayout.LayoutParams 中可用,而 layout_aboveRelativeLayout.LayoutParams 中可用。目前,我正在做

LinearLayout ll_menu_code = new LinearLayout(this);
        ll_menu_code.setId(1001);
        LinearLayout.LayoutParams parmas_ll_menu_code = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 2f);
        parmas_ll_menu_code.setMargins(0, 20, 0, 0);
        ll_menu_code.setLayoutParams(parmas_ll_menu_code);

设置了weightSum。如何设置layout_above?这两个属性应该怎么设置?

我想以编程方式创建以下 xml 布局

<LinearLayout
                                android:layout_below="@id/ll_menu_code"
                                android:id="@+id/ll_quantity"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_marginTop="20dp"
                                android:weightSum="5">

如果您想以编程方式将 LinearLayout 添加到 RelativeLayout,那么您必须创建 RelativeLayout.LayoutParams 而不是 LinearLayout.LayoutParams 的实例,因为 LinearLayout 是 child 到 Relativelayout

所以你的代码必须是

LinearLayout ll_menu_code = new LinearLayout(this);
    ll_menu_code.setId(1001);
    ll_menu_code.setWeightSum(2f);        

    RelativeLayout.LayoutParams parmas_ll_menu_code = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    parmas_ll_menu_code.setMargins(0, 20, 0, 0);
    parmas_ll_menu_code.addRule(RelativeLayout.BELOW, 1001);

    ll_menu_code.setLayoutParams(parmas_ll_menu_code);

希望对你有帮助..