在android中创建一个像视图一样的动态网格

时间:2014-01-27 17:01:31

标签: android android-layout android-linearlayout

为了在android中创建像图像这样的结构,我尝试了以下代码。

但显示此错误。请帮忙

我的代码看起来像

public void setValues(){

    LinearLayout table=(LinearLayout)findViewById(R.id.mainWrap);

    LinearLayout row=new LinearLayout(this);;
    for(int i=0;i<5;i++){

        if(i%2==0){

        row= new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        }


        FrameLayout layout = new FrameLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((width/2)-10,(height/2)-10);
        params.setMargins(5, 5, 5, 5);
        layout.setLayoutParams(params);

        if(i%2==0){
        layout.setBackgroundColor(Color.parseColor("#CACACA"));
        }
        else {
            layout.setBackgroundColor(Color.parseColor("#333333"));
        }

        ProgressBar pr=new ProgressBar(this);
        FrameLayout.LayoutParams params_p = new FrameLayout.LayoutParams((width/6),(width/6));
        params_p.gravity=Gravity.CENTER;
        pr.setLayoutParams(params_p);
        layout.addView(pr);



        ImageView im=new ImageView(this);
        FrameLayout.LayoutParams params_im = new FrameLayout.LayoutParams((width/2),(width/2));
        im.setImageResource(R.drawable.man);

        im.setLayoutParams(params_im);
        layout.addView(im);

        row.addView(layout);
        table.addView(row);
    }

错误是

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

enter image description here

提前致谢

1 个答案:

答案 0 :(得分:0)

我有一种感觉问题就在这里:

  LinearLayout row=new LinearLayout(this);;
  for(int i=0;i<5;i++){

它第一次循环row将被你的第二次赋值替换并保存在循环的变量OUTSIDE中,第二次它没有被替换,因为它在循环之外,它是您尝试再次添加row的{​​{1}}相同。只需交换上面一行的顺序。