RVG
RVG

Reputation: 3576

Re-arrange the view order on Framelayout android

I've add five views on frameLayout.

how to re arrange the childIndex of framelayout.

i use below code:

fromindex  = 3;
toindex    = 4;
View tempFrom = frameLayout.getChildAt(fromindex);
View tempTo   = frameLayout.getChildAt(toindex);
frameLayout.removeViewAt(fromindex)
frameLayout.removeViewAt(toindex)
frameLayout.addView(tempFrom, toindex)
frameLayout.addView(tempTo,fromindex)

But its throws the below error.

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

How to re arrange the childindex of framelayout ?

Upvotes: 3

Views: 5949

Answers (3)

user
user

Reputation: 87064

how to re arrange the childIndex of framelayout.

The FrameLayout doesn't have the ability to re arrange its children directly but you can do it by removing those children and re adding them in the right positions. Your code doesn't work because you remove the views in an incorrect order resulting in views still being attached to the parent:

fromindex  = 3;
toindex    = 4;
View tempFrom = frameLayout.getChildAt(fromindex);
View tempTo   = frameLayout.getChildAt(toindex);
// first remove the view which is above in the parent's stack
// otherwise, if you remove the other child you'll call the `removeViewAt`
// method with the wrong index and the view which was supposed to be detached
// from the parent is still attached to it
frameLayout.removeViewAt(toindex);
frameLayout.removeViewAt(fromindex);
// first add the child which is lower in the hierarchy so you add the views
// in the correct order
frameLayout.addView(tempTo,fromindex)
frameLayout.addView(tempFrom, toindex)

Upvotes: 4

Mert
Mert

Reputation: 6572

You can't swap views I think. You need to define new view group and inflate to his parent and remove old one.

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

Upvotes: 0

Ali Imran
Ali Imran

Reputation: 9217

Try this code

frameLayout.removeView(tempFrom) //to remove views
frameLayout.removeView(tempTo)

Upvotes: 0

Related Questions