在Framelayout android上重新排列视图顺序

时间:2012-12-11 11:54:14

标签: android

我在frameLayout上添加了五个视图。

如何重新安排framelayout的childIndex。

我使用下面的代码:

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)

但它引发了以下错误。

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

如何重新安排framelayout的子索引?

3 个答案:

答案 0 :(得分:4)

  

如何重新安排framelayout的childIndex。

FrameLayout无法直接重新安排其子项,但您可以通过删除这些子项并将其添加到正确的位置来实现。您的代码不起作用,因为您以错误的顺序删除了视图,导致视图仍然附加到父级:

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)

答案 1 :(得分:0)

试试此代码

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

答案 2 :(得分:0)

我认为你不能交换意见。您需要定义新的视图组并向其父级充气并删除旧的视图组。

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);