Reputation: 1389
I have created this extension function for navigating between fragments which is pretty straight forward but somehow it's not working. it's not doing anything and nothing changes when I click the button. I think the problem is with this@navigate
argument but I don't see why that should be a problem.
fun Fragment.navigate(): Int? {
return fragmentManager?.run {
beginTransaction()
.replace(
R.id.my_container,
this@navigate,
this@navigate::class.simpleName
)
.commit()
}
}
and the usage is like this
class TestTwoFragment : Fragment(R.layout.fragment_test_two) {
....
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
goto_three.setOnClickListener {
TestThreeFragment
.newInstance()
.navigate()
}
}
Upvotes: 0
Views: 477
Reputation: 7121
You're using the fragmentManager
of the new fragment which will be null
if the fragment hasn't been added yet, like in your case. Since you're using ?.run
, nothing happens and the method returns null
.
Consider adding a fragment manager parameter to your method:
fun Fragment.navigate(fm: FragmentManager): Int? {
return fm.run {
beginTransaction()
.replace(
R.id.my_container,
this@navigate,
this@navigate::class.simpleName
)
.commit()
}
}
And then:
TestThreeFragment
.newInstance()
.navigate(getParentFragmentManager())
Upvotes: 3