Dynamically open one fragment from another fragment in Android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Dynamically open one fragment from another fragment in Android

Postby vivekkalady » Mon Nov 24, 2014 2:55 pm

Fragments are usually loaded into FrameLayout

Your xml will be like this

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


 <FrameLayout android:name="fragments.YourInitialFragment"
            android:id="@+id/fragment_container"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="0dip" />

</LinearLayout>


The Fragments are loaded into fragment_container

The code for doing it is given below

Code: Select all

NextFragment nextFrag= new NextFragment();
     this.getFragmentManager().beginTransaction()
     .replace(R.id.fragment_container, nextFrag,TAG_FRAGMENT)
     .addToBackStack(null)
     .commit();



If you add this line .addToBackStack(null), your current fragment will go to backstack and the new one will be shown to screen.
so if you press back button, the previous fragment will be loaded to the fragment_container.If you don't want that remove the line.

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron