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

大兔子大兔子 提交于 2019-12-24 08:47:23

问题


I am mking an android app in which i am making dynamically table rows and then adding imageviews and textviews to it dynamically. It adds the first row and then give the following exception

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

I am using the following code for it:

          ar1= new JSONArray(children.toString());
                                for(int mn=0;mn<ar1.length();mn++){
                                    value=ar1.getString(mn);
    TableRow tr = new TableRow(HomePageWithPhoneIsOfflineDialog.this);
                                    tr.setBackgroundColor(Color.WHITE);
                                    tr.setId(100+mn);
                                    tr.setMinimumHeight(60);
                                    tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                                    TextView child= new TextView(HomePageWithPhoneIsOfflineDialog.this);
                                    child.setId(200+mn);
                                    child.setHeight(50);
                                    child.setGravity(Gravity.CENTER);
                                    child.setTextColor(Color.BLACK);
                                    System.out.println(value);
                                    child.setText(value);
                                    System.out.println("adding iv");
                                    tr.addView(iv,0);
                                    System.out.println("adding child");
                                    tr.addView(child);
                                    System.out.println("adding table row");
                                     table.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

}

Can anyone tell me how to solve this problem.

THAnks


回答1:


The iv variable that you are adding, is not been created inside the loop so I imagine is created before... but in the second loop it's added to two different Table Rows.




回答2:


tr.addView(iv,0);

Problem is with the ImageView (iv), i think, since it is not instantiated inside the loop, so first time it was added to a row, and when you add it again to another row, it doesn't permit, because a view can have only 1 parent.

so i would suggest you to create a new ImageView for every time you loop.




回答3:


because you are adding same View with new value in each iteration .

initialize imageView iv ,before tr.addView(iv,0);

ImageView in = new ImageView(ctx)


来源:https://stackoverflow.com/questions/8132867/android-java-lang-illegalstateexception-the-specified-child-already-has-a-pare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!