In my custom view I use the below simple method to change child views dynamically:
private void changeChildView(final View oldView, final View newView) {
final int viewIndex = indexOfChild(oldView);
removeViewAt(viewIndex);
addView(newView, viewIndex);
}
In the beginning childView1 is placed on on the ViewGroup. As soon as the user triggers a gesture on childView1, I do following steps:
I store childView1 in a global variable in my custom view:
mTempView = childView1
then I inflate childview2
changeChildView(childView1, childView2)
It works like a charm. But if user hits back button I need to revert back to childView1 that is supposed to be stored in the global variable at this point. I do revert by:
changeChildView(childView2, mTempView)
But the revert doesn't work. I checked that the mTempView contains the view but it never shows up. Strangely it shows up as soon as I rotate which means that the the view was successfully added back in the revert process.