I am running into a problem with RelativeLayout
and ViewSwitcher
here and maybe someone is able to help. So what I want is switching two views using a ViewSwitcher
, however, the fact that a switcher is even part of the equation should be hidden from the user/developer; instead, they should only ever deal with either one of the two views that are being switched.
For this to work, what I am doing is provide a custom widget which upon inflation, removes itself from the view tree, inserts a ViewSwitcher
in its previous position, and then re-inserts itself as a child of the view switcher. That part works fine.
If now I have two of these views, positioning them relative to the parent (e.g. using layout_alignParentBottom
) works just fine, but not when I try to position them relative to each other using e.g. layout_toRightOf=id
.
It does work, however, when I copy the switched view's ID over to the ViewSwitcher (its new parent), but I don't understand why that is necessary and will probably rain frogs or something when having more than one view with the same ID in the view tree?
Here's some code for clarification:
// 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);
}
}
Then in a layout XML file, the user merely needs to inflate this custom view:
<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" ... />
in other words, since layout_toRightOf
becomes an attribute of the new ViewSwitcher
, while the ID remains an attribute of the custom view, aligning the switcher relative to a view that's a child of another view switcher does not work, and I have no idea why. Only if I also give the switcher the same ID as its child then positioning will work.
Any pointers as to what's going wrong here?