Home > OS >  How to move to home fragment by pressing back button
How to move to home fragment by pressing back button

Time:04-07

I have created a custom navigation drawer using motion layout in which I have image views, text views and a nav host fragment(fragment container view). The Problem is, When I click any view in my navigation drawer, it opens a fragment but when clicked the back button, it closes the application.

This is my mainactivity.kt file

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val contactus = findViewById<TextView>(R.id.contact_us)
        val drawer = findViewById<ImageView>(R.id.image8)
        val tandc = findViewById<TextView>(R.id.termsandconditions)
        val motionLayout = findViewById<MotionLayout>(R.id.motion_layout)


        contactus.setOnClickListener {

            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, contact_us_fragment())
                commit()

                motionLayout.transitionToStart()


            }
        }
        drawer.setOnClickListener {

            motionLayout.transitionToEnd()
            motionLayout.transitionToStart()
        }
        tandc.setOnClickListener {
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, TandCFragment())
                commit()

                motionLayout.transitionToStart()

            }
        }
    }
}

I'm new to android development. How can I Move to home fragment on back button press. Please suggest me, how to do this

CodePudding user response:

I believe you have to implement the onBackPressed() method. This gets called when the user presses / swipes back.

override fun onBackPressed() {
    // Code here to handle going to fragment
}

CodePudding user response:

You can add fragment to back stack and give them id, and then pop the back stack with this id.

 override fun onBackPressed() {
    super.onBackPressed()
    supportFragmentManager.beginTransaction()
    .add(yourFragment);
    .addToBackStack("YourFragmentTag");
 }

And then pop the stack to this fragment by

getFragmentManager().popBackStack("YourFragmentTag", 0);
  • Related