I am attempting to create an Activity which contains some TextViews at the top and then two Fragments below, side to side. The left Fragment contains a LinearLayout with clickable TextViews which are used to allow the user to determine which Fragment is displayed on the right. How can I reserve the Fragment space on the right so that I can dynamically switch the Fragments out?
My current attempt looks like this:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- TextViews go here -->
<fragment
android:id="@+id/fragmentSelector"
android:name="com.metastable.android.pe.FragmentSelector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/empireNameTV"
android:layout_below="@+id/empireNameTV" />
<fragment
android:id="@+id/fragmentScreen"
android:name="com.metastable.android.pe.FragmentSummary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignTop="@+id/fragmentSelector"
android:layout_toRightOf="@+id/fragmentSelector" />
</RelativeLayout>
fragmentSelector for the moment will always be there so having it loaded at the creation of the activity is fine, the issue is with my fragmentScreen. As it stands it will load FragmentSummary which looks fine but when I attempt to replace it it’s layout remains in the background with the new Fragment laying on top of it. Here’s how I do the replace:
public void onScreenSelected(int screen) {
Log.d("PE", "ScreenSelected called!");
if (screen == currentScreen)
return;
FragmentTransaction ft = fm.beginTransaction();
switch (screen) {
case SUMMARY:
ft.replace(R.id.fragmentScreen, fragmentSummary);
currentScreen = SUMMARY;
break;
case PLANET_MANAGER:
ft.replace(R.id.fragmentScreen, fragmentPlanetManager);
currentScreen = PLANET_MANAGER;
break;
}
ft.commit();
}
My guess is that you cannot replace a fragment that was loaded from a layout so I need a way to save the space in the layout and load the Fragments programmatically. Any suggestions are appreciated.
A work around in my opinion is making the unwanted fragments invisible.
Like below,
Now you can hide the fragment by making it’s parent frame layout invisible or gone.
I hope this will solve your problem..