Hello Androiders, Welcome to the Android Fragments Kotlin Backstack example tutorial.
In Android Fragments Kotlin Backstack Example, learn how to create a basic fragment with simple a example and source code.
You will learn how to create multiple fragments in one activity.
We will cover how to maintain,handle and manage backstack of fragments.
First, check the output of Android Fragments Kotlin Backstack, then we will develop it.
Download Source Code For Android Fragments Kotlin Backstack Example
[sociallocker]Download Kotlin Android Fragment Backstack[/sociallocker]
Step 1: Create a new project in Android Studio.
Make sure you are ready with new android project in android studio.
Step 2: Creating Two Fragments
Prepare two fragments and give them name as “OneFragment” and “TwoFragment.”
Add below code in OneFragment.kt
import android.content.Context import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class OneFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_one, container, false) } }
Paste following source code in fragment_one.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" tools:context="com.example.parsaniahardik.kotlinbasicfragment.OneFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="25sp" android:gravity="center" android:textColor="#fff" android:text="Fragment One" /> </FrameLayout>
Add below code in TwoFragment.kt
import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class TwoFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_two, container, false) } }
Copy following in fragment_two.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimary" tools:context="com.example.parsaniahardik.kotlinbasicfragment.TwoFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="25sp" android:gravity="center" android:textColor="#fff" android:text="Fragment Two" /> </FrameLayout>
Step 3: Making BackStack Activity
Create a new activity and give it a name “BackStackActivity.”
Copy following in activity_back_stack.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.parsaniahardik.kotlinbasicfragment.BackStackActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_weight="1" android:id="@+id/btnfr1with" android:layout_height="wrap_content" android:text="Frag. 1 with backstack" /> <Button android:layout_width="0dp" android:layout_weight="1" android:id="@+id/btnfr2with" android:layout_height="wrap_content" android:text="Frag. 2 with backstack" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/container_frame_back" android:layout_marginTop="5dp" android:orientation="horizontal"> </LinearLayout> </LinearLayout>
Add below in BackStackActivity.kt
import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class BackStackActivity : AppCompatActivity() { private var btnFrag1WithBack: Button? = null private var btnFrag2WithBack: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_back_stack) btnFrag1WithBack = findViewById(R.id.btnfr1with) as Button btnFrag2WithBack = findViewById(R.id.btnfr2with) as Button btnFrag1WithBack!!.setOnClickListener { addFragment(OneFragment(), true, "one1") } btnFrag2WithBack!!.setOnClickListener { addFragment(TwoFragment(), true, "two2") } } fun addFragment(fragment: Fragment, addToBackStack: Boolean, tag: String) { val manager = supportFragmentManager val ft = manager.beginTransaction() if (addToBackStack) { ft.addToBackStack(tag) } ft.replace(R.id.container_frame_back, fragment, tag) ft.commitAllowingStateLoss() } }
Step 4: Description of BackStackActivity
Below function is used to create a fragment.
fun addFragment(fragment: Fragment, addToBackStack: Boolean, tag: String) { val manager = supportFragmentManager val ft = manager.beginTransaction() if (addToBackStack) { ft.addToBackStack(tag) } ft.replace(R.id.container_frame_back, fragment, tag) ft.commitAllowingStateLoss() }
In the second parameter, a boolean variable “addToBackStack” is passed.
If addToBackStack is true then, the fragment will be saved in back stack. That means when a user clicks on the back button all the fragments present in backstack will be set in container_frame as per its order.
Step 5: Updating MainActivity
Add below to activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.parsaniahardik.kotlinbasicfragment.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_weight="1" android:id="@+id/btnfr1without" android:layout_height="wrap_content" android:text="Frag. 1 without backstack" /> <Button android:layout_width="0dp" android:layout_weight="1" android:id="@+id/btnfr2without" android:layout_height="wrap_content" android:text="Frag. 2 without backstack" /> </LinearLayout> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnback" android:text="fragment with backstack"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/container_frame" android:layout_marginTop="5dp" android:orientation="horizontal"> </LinearLayout> </LinearLayout>
Add following in MainActivity.kt
import android.content.Intent import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class MainActivity : AppCompatActivity() { private var btnFrag1WithoutBack: Button? = null private var btnFrag2WithoutBack: Button? = null private var btnback: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnFrag1WithoutBack = findViewById(R.id.btnfr1without) as Button btnFrag2WithoutBack = findViewById(R.id.btnfr2without) as Button btnback = findViewById(R.id.btnback) as Button btnback!!.setOnClickListener { val intent = Intent(this@MainActivity, BackStackActivity::class.java) startActivity(intent) } btnFrag1WithoutBack!!.setOnClickListener { addFragment(OneFragment(), false, "one") } btnFrag2WithoutBack!!.setOnClickListener { addFragment(TwoFragment(), false, "two") } } fun addFragment(fragment: Fragment, addToBackStack: Boolean, tag: String) { val manager = supportFragmentManager val ft = manager.beginTransaction() if (addToBackStack) { ft.addToBackStack(tag) } ft.replace(R.id.container_frame, fragment, tag) ft.commitAllowingStateLoss() } }
Step 6: Description of MainActivity
Following function is used to open fragment.
fun addFragment(fragment: Fragment, addToBackStack: Boolean, tag: String) { val manager = supportFragmentManager val ft = manager.beginTransaction() if (addToBackStack) { ft.addToBackStack(tag) } ft.replace(R.id.container_frame, fragment, tag) ft.commitAllowingStateLoss() }
Same as in BackStackActivity, a boolean addToBackStack variable is passed in the second parameter.
Here it is false, so if a user clicks back button, the app will be closed because nothing was saved in the backstack.
Java Version
Java version of this tutorial is available here: Fragments Android Tutorial.
So that is all for Fragments Android Kotlin Backstack example.
Feel free to comment your queries and reviews in the comment section. Thank you.