3

我在 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 的 childindex ?

4

3 回答 3

4

如何重新排列framelayout的childIndex。

TheFrameLayout没有能力直接重新安排其孩子,但您可以通过删除这些孩子并将它们重新添加到正确的位置来做到这一点。您的代码不起作用,因为您以不正确的顺序删除视图导致视图仍附加到父级:

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)
于 2012-12-11T14:42:27.880 回答
0

试试这个代码

frameLayout.removeView(tempFrom) //to remove views
frameLayout.removeView(tempTo)
于 2012-12-11T12:03:23.580 回答
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);
于 2012-12-11T12:42:48.660 回答