How to work with back button in android with multiple fragment

How to work with back button in android with multiple fragment
December 6, 2018 No Comments Android Development,Development Pushpendra Kumar



How to work with back button in android with multiple fragment

When I was developing the Android application I found the very common issue. That was, how to manage back button navigation if I am using multiple fragments.
On some particular fragment, I want to show the back button but on some fragment, I don’t want to show the back button. Something like this and it may be varied as per your requirement. Here I am just considering a basic example with three fragments. I hope this example will surely help you with your problem. And this tutorial is completely written in Kotlin Language.

In this example I have Three fragment and one activity. Here I am taking navigation like – Fragment One -> Fragment Two -> Fragment Three. This is forward Navigation.

Now the Back-word navigation will be like Fragment Three -> Fragment One & Fragment Two -> Fragment One.

Code for MainActivity in Kotlin – MainActivity.kt

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportFragmentManager.beginTransaction().replace(R.id.container, OneFragment()).commit()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        onBackPressed()
        return super.onOptionsItemSelected(item)
    }

    private var doubleBackToExitPressedOnce = false
    @SuppressLint("ObsoleteSdkInt")
    override fun onBackPressed() {
        val f = supportFragmentManager.findFragmentById(R.id.container)
        when (f) {
            is OneFragment -> {
                if (doubleBackToExitPressedOnce) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        finishAffinity()
                    } else {
                        finish()
                    }
                }
                this.doubleBackToExitPressedOnce = true
                setSnackBar("Please click BACK again to exit")
                Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            }
            is ThreeFragment -> supportFragmentManager.beginTransaction()
                .replace(R.id.container, OneFragment())
                .addToBackStack("tag").commit()
            else -> super.onBackPressed()
        }

    }

    private fun setSnackBar(message: String) {
        val snackBar = Snackbar.make(this.findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG)
        snackBar.show()
    }
}




XML Of Main Activity! activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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"
        tools:context=".MainActivity">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.constraint.ConstraintLayout>

Now I am writhing the code of OnCreate() of Fragment One! OneFragment.kt

private var rootView: View? = null
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_one, container, false)


    if (activity != null) {
        (activity as MainActivity).title = "Fragment One"
    }
    if ((activity as MainActivity).supportActionBar != null) {
        val actionBar = (activity as MainActivity).supportActionBar
        actionBar!!.setDisplayHomeAsUpEnabled(false)
        actionBar.setHomeButtonEnabled(false)
    }
    val button: Button = rootView!!.findViewById(R.id.btnClick)
    button.setOnClickListener {
        activity!!.supportFragmentManager.beginTransaction().replace(R.id.container, TwoFragment()).addToBackStack("tag").commit()
    }

    return rootView
}

XML Of Fragment one! fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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"
        tools:context=".OneFragment">

        <Button
            android:id="@+id/btnClick"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_margin="20dp"
            android:text="Fragment Two"
            android:textSize="17sp"
            android:textStyle="bold" />

    </RelativeLayout>

Code for Fragment Two OnCreate() in Kotlin – TwoFragment.kt

private var rootView: View? = null
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_two, container, false)

    if (activity != null) {
        (activity as MainActivity).title = "Fragment Two"
    }
    if ((activity as MainActivity).supportActionBar != null) {
        val actionBar = (activity as MainActivity).supportActionBar
        actionBar!!.setDisplayHomeAsUpEnabled(true)
        actionBar.setHomeButtonEnabled(true)
    }

    val button = rootView!!.findViewById<Button>(R.id.btnClick)
    button.setOnClickListener {
        activity!!.supportFragmentManager.beginTransaction().replace(R.id.container, ThreeFragment()).addToBackStack("tag").commit()
    }
    return rootView
}


Xml of Fragment Two! fragment_two.xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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"
        tools:context=".TwoFragment">

        <Button
            android:id="@+id/btnClick"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_margin="20dp"
            android:text="Fragment Three"
            android:textSize="17sp"
            android:textStyle="bold" />

    </RelativeLayout>

Code for Fragment Three OnCreate() in Kotlin – ThreeFragment.kt

private var rootView: View? = null
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_three, container, false)

    if (activity != null) {
        (activity as MainActivity).title = "Fragment Three"
    }
    if ((activity as MainActivity).supportActionBar != null) {
        val actionBar = (activity as MainActivity).supportActionBar
        actionBar!!.setDisplayHomeAsUpEnabled(true)
        actionBar.setHomeButtonEnabled(true)
    }
    return rootView
}

Here Xml of Fragment Three is default.


Tags
About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd (www.thecolourmoon.com). This website I have made so that I can meet with new challenges and can share here.

Leave a reply

Your email address will not be published. Required fields are marked *