0

I' m trying to add my custom PostLayout class, it adds first one but after that it crashes with this error;

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

    FragmentPostLayout = (LinearLayout) view.findViewById(R.id.HomeFragmentGenerateLayout);
    PostLayout postlayout = new PostLayout(context);
    for(int i = 0; i < 10; i++)
        FragmentPostLayout.addView(postlayout, i - 1);//where it crashes when i=1
4
  • try removing the second parameter of addView (meaning use this: developer.android.com/reference/android/view/… ) . It seems you try to put it as the last view anyway. Try calling just : FragmentPostLayout.addView(postlayout); Commented Feb 7, 2016 at 15:59
  • still have the same error. Commented Feb 7, 2016 at 16:01
  • 1
    Oh, I know what's wrong: you add the same view. If you wish to add multiple views, you have to create multiple views. the "new PostLayout" is supposed to be inside the loop, and not outside of it. Commented Feb 7, 2016 at 16:50
  • Yes, you are right thanks! @androiddeveloper Commented Feb 7, 2016 at 16:53

1 Answer 1

1

This error usually is caused because you're adding a view that is already on the screen.

On the first loop of your iteration you add the PostLayout, and on the second you try re-adding it - and that's why the loop crashes when the index is 1.

Try creating a new post layout every time:

for(int i = 0; i < 10; i++)
    MyView view = new MyView(context);
    ParentView.addView(view);
Sign up to request clarification or add additional context in comments.

1 Comment

That was the issue! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.