skip to Main Content

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()

            }
        }
    }
}

How can I Move to home fragment on back button press?

2

Answers


  1. 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
    }
    
    
    Login or Signup to reply.
  2. You can add fragment to back stack and give them id, and then pop the back stack with this id.

        supportFragmentManager.beginTransaction()
        .add(yourFragment);
        .addToBackStack("YourFragmentTag");
        .commit()
     
    

    And then pop the stack to this fragment by

     override fun onBackPressed() { 
        getFragmentManager().popBackStack("YourFragmentTag", 0);
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search