Sandeep Nautiyal
Sandeep Nautiyal

Reputation: 111

linearLayout.addView(index, view) gives IllegalStateException

Please have a look at the code fragment given below :-

private void updateActivityView() 
{
    for(int i = 0; i < numberOfLinearLayouts; i++)
    {
        LinearLayout linearLayout = linearLayouts.get(i);

        linearLayout.removeAllViews();

        int index = 0;

        for(int j = i; j < childFrames.size(); j = j+numberOfLinearLayouts)
        {
            FrameLayout frameLayout = childFrames.get(j);

            frameLayout.setLayoutParams(frameLayoutParams);

            linearLayout.addView(frameLayout, index);

            index++;
        }
    }           
}

gives "IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first." It works fine when a single framelayout is added to the linearlayout, but when i am trying to add more than one framelayout on the same linear layout it gives me this exception.

Code for creating framelayout is given below:-

FrameLayout frameLayout = (FrameLayout)getLayoutInflater().inflate(R.layout.xyz_frame_layout, null, false);

int id = XYZ.getId(); //generates a random number. uniqueness guaranteed.

frameLayout.setId(id);  

Method getId() shown above generates a random number. uniqueness of id is guaranteed.

Please help me in finding the problem in the code snippet. Thank in advance.

Upvotes: 0

Views: 353

Answers (1)

Abhinav Arora
Abhinav Arora

Reputation: 537

You are receiving this error because framelayout already has a parent. Try something like

FrameLayout framelayout = new FrameLayout(context);

I cant provide you the exact code as I am unable to understand your code but the problem you are facing is definitely because of the reason stated above. The framelayout already has a parent and you are again giving it a parent. Hence the problem !!

Upvotes: 1

Related Questions