3

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 ?

RVG
  • 3,538
  • 4
  • 37
  • 64

3 Answers3

4

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)
user
  • 86,916
  • 18
  • 197
  • 190
  • This command is very useful ... thank u..// 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 – RVG Dec 12 '12 at 04:56
  • @Ganesh Is there a problem? – user Dec 12 '12 at 04:59
0

Try this code

frameLayout.removeView(tempFrom) //to remove views
frameLayout.removeView(tempTo)
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
0

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);
Mert
  • 6,432
  • 6
  • 32
  • 68