I recently asked a question about fragments here:
http://stackoverflow.com/questions/12443312/listview-not-populating-or-webview-taking-up-entire-screen
After a lot of messing around I found what the problem was, but after more fooling around, and research (in which correct code seemed identical to mine), i cant figure out what my problem is.
After everything is created, I find that only the last fragment added to the transaction is visible. This is my code to add them:
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
UrlListFragment urlfragment = new UrlListFragment();
MyWebFragment webfragment = new MyWebFragment();
trans.add(R.id.fragment_container, urlfragment, "my_url_fragment");
trans.add(R.id.fragment_container, webfragment, "my_web_fragment");
trans.commit();
And this is my main xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
What am I doing wrong, or what can be done so both fragments are added correctly and can be seen correctly?
Unfortunately you cant use fragments in this way you need to use just one fragment per container. It will amount to the same visual layout anyway.
and
To add multiple fragments inside one layout, you need to call
add()
andcommit()
methods for each individual fragment. But if you're adding your fragments in a loop, or for example like below:This might also get you into some problems. Since, the
commit()
method doesn't add the fragment immediately, you need to make sure that the previous fragment was attached from activity'sonAttachFragment()
method and then move further adding another fragment.