layoutLelout的layout_below和weightsum以编程方式

时间:2016-05-05 08:11:47

标签: android android-layout android-linearlayout android-relativelayout

我正在以编程方式在LinearLayout中创建RelativeLayout。我要做的是在weigtsum中分配LinearLayout,并且还要设置layout_above属性。 weightSum中存在问题LinearLayout.LayoutParamslayout_above中可以使用RelativeLayout.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">

1 个答案:

答案 0 :(得分:5)

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

所以你的代码必须是

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);

我希望它有所帮助......