【问题标题】:Re-arrange the view order on Framelayout android重新排列Framelayout android上的视图顺序
【发布时间】:2012-12-11 22:42:27
【问题描述】:

我在 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如何重新排列?

【问题讨论】:

    标签: android


    【解决方案1】:

    如何重新排列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)
    

    【讨论】:

    • 这个命令非常有用...谢谢你..// 首先删除父堆栈中的视图,否则,如果删除另一个子视图,您将调用 'removeViewAt` 方法索引错误,并且应该与父级分离的视图仍然附加到它
    • @Ganesh 有问题吗?
    【解决方案2】:

    试试这个代码

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

    【讨论】:

      【解决方案3】:

      我认为你不能交换意见。您需要定义新的视图组并膨胀到他的父级并删除旧的。

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

      【讨论】:

      • C 应为小写以符合 java 标准
      猜你喜欢
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多