1

我在这里遇到了问题,RelativeLayout也许ViewSwitcher有人可以提供帮助。所以我想要的是使用 a 切换两个视图ViewSwitcher,但是,切换器甚至是等式的一部分这一事实应该对用户/开发人员隐藏;相反,他们应该只处理正在切换的两个视图中的任何一个。

为此,我正在做的是提供一个自定义小部件,该小部件在膨胀时会从视图树中移除,ViewSwitcher在其先前位置插入 a,然后将自身重新插入为视图切换器的子项。那部分工作正常。

如果现在我有两个这样的视图,将它们相对于父级(例如使用layout_alignParentBottom)定位就可以了,但是当我尝试使用例如将它们相对于彼此定位时就不行了layout_toRightOf=id

但是,当我将切换视图的 ID 复制到 ViewSwitcher (它的新父级)时,它确实有效,但我不明白为什么这是必要的,并且当拥有多个具有相同 ID 的视图时,可能会下雨青蛙或其他东西在视图树中?

这是一些澄清的代码:

// onLayout of the custom view that automatically inserts itself under a ViewSwitcher
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);

    if (!(getParent() instanceof ViewSwitcher)) {

        // uncommenting this line fixes the issue,
        // but I don't want duplicate IDs!
        //switcher.setId(getId());

        // "migrate" this view's LPs to the new parent
        switcher.setLayoutParams(getLayoutParams());

        ViewGroup parent = (ViewGroup) this.getParent();
        System.out.println("PARENT: " + parent);
        int selfIndex = parent.indexOfChild(this);
        parent.removeView(this);
        parent.addView(switcher, selfIndex);

        ViewSwitcher.LayoutParams newParams = new ViewSwitcher.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        switcher.addView(this, newParams);
    }
}

然后在一个布局 XML 文件中,用户只需要扩展这个自定义视图:

<com.myview.CustomView android:id="@+id/one" ... />
<!-- this works: -->
<com.myview.CustomView android:layout_alignParentTop="true" ... />
<!-- this doesn't without the ID hack: -->
<com.myview.CustomView android:layout_toRightOf="@id/one" ... />

换句话说,因为layout_toRightOf成为 new 的属性ViewSwitcher,而 ID 仍然是自定义视图的属性,将切换器相对于另一个视图切换器的子视图对齐不起作用,我不知道为什么。只有当我也给切换器提供与它的孩子相同的 ID 时,定位才会起作用。

关于这里出了什么问题的任何指示?

4

1 回答 1

1

不确定我是否正确,但是当您将视图相对于彼此定位时,视图是否必须位于视图层次结构的同一级别?

因此,也许您应该以另一种方式定义您的引用: View one 具有该android:layout_toRLeftOf"@id/two属性,一旦您创建了该属性,ViewSwitcher您只需复制孩子的布局参数。

于 2012-05-03T09:39:33.803 回答