Boyfinn
Boyfinn

Reputation: 311

Kotlin opening new fragment in nav drawer example

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.

Upvotes: 0

Views: 308

Answers (1)

Zain
Zain

Reputation: 40810

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

Upvotes: 1

Related Questions