动态添加复选框到多个片段布局

时间:2015-09-16 10:58:32

标签: android android-layout android-fragments android-checkbox

我正在尝试根据从数据库中获取的数据动态创建复选框,单个片段中最多6个,如果超过6个,则在下一个片段中显示它们等......

这是我到目前为止所获得的代码:

for(int i=0;i<size; i+=2){
        RelativeLayout rl=new RelativeLayout(CreateFuelOnlyInspectionActivity.this);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        int rlMarginTop_px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
        lp.topMargin=rlMarginTop_px;
        rl.setLayoutParams(lp);

        CheckBox cb1=new CheckBox(CreateFuelOnlyInspectionActivity.this);
        cb1.setId(1);
        cb1.setTag(""+i);

        RelativeLayout.LayoutParams cbParams1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        cb1.setLayoutParams(cbParams1);
        cb1.setButtonDrawable(getResources().getDrawable(R.drawable.checkbox_selector));
        rl.addView(cb1);

但这只处理一个片段。我该如何将其扩展到更多?

1 个答案:

答案 0 :(得分:0)

把你的代码放在:

    RelativeLayout rl=new RelativeLayout(CreateFuelOnlyInspectionActivity.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    int rlMarginTop_px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
    lp.topMargin=rlMarginTop_px;
    rl.setLayoutParams(lp);

    CheckBox cb1;

    RelativeLayout.LayoutParams cbParams1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    for(int i=0;i<=6; i++){

        cb1=new CheckBox(CreateFuelOnlyInspectionActivity.this);
        cb1.setId(i);
        cb1.setTag(""+i);
        cb1.setLayoutParams(cbParams1);
        cb1.setButtonDrawable(getResources().getDrawable(R.drawable.checkbox_selector));
        rl.addView(cb1);
    }       
// enable view page here