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
I believe you have to implement the
onBackPressed()
method. This gets called when the user presses / swipes back.You can add fragment to back stack and give them id, and then pop the back stack with this id.
And then pop the stack to this fragment by