Issue
I'm relatively new with Kotlin and I'm trying to extend the navigation drawer example by adding a button into my fragment that can open another fragment directly without having to select it from the navigation drawer.
Here is my button listener in my fragment's onCreateView
function:
addButton.setOnClickListener()
{
Toast.makeText(this.context,"ButtonPressed",Toast.LENGTH_SHORT).show()
this.activity.supportFragmentManager.beginTransaction().replace(R.id.mobile_navigation, R.layout.fragment2).commit()
}
I'm not sure I completely understand how to approach this. The button works fine and calls the toast, but I can't get it to change the fragment.
Any help would be appreciated.
Solution
the template has a mobile_navigation.xml file with a "navigation" element.
The Navigation Architecture components is used by default in recent android studio versions, so the navController
is the responsible for fragment transaction instead of doing that manually by the supportFragmentManager
addButton.setOnClickListener() {
Toast.makeText(this.context,"ButtonPressed",Toast.LENGTH_SHORT).show()
val navHostFragment = requireActivity().supportFragmentManager
.primaryNavigationFragment as NavHostFragment
navHostFragment.navController.navigate(R.layout.fragment2)
}
Also, make sure that R.layout.fragment2
is the fragment id of the destination fragment in the R.id.mobile_navigation.xml
Answered By - Zain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.