I have a toolbar in activity with a fragment container
<androidx.appcompat.widget.Toolbar
android:id="@ id/tlUsersActivity"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/white"
/>
I run these lines to control the backpressed button
setSupportActionBar(binding?.tlUsersActivity)
if (supportActionBar != null) {
when (intent.getStringExtra(MainActivityAdmin.FRAGMENT_TYPE)) {
"View Users" -> {
supportActionBar?.title = viewUsersText
}
"Edit Users" -> {
supportActionBar?.title = editUsersText
}
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding?.tlUsersActivity?.setNavigationOnClickListener { onBackPressed() }
I want to change this action from inside the fragment, I want to replace it with a function that replaces fragments. I've tried this but it didn't work
val actionBar = view?.findViewById<Toolbar>(R.id.tlUsersActivity)
actionBar?.setNavigationOnClickListener {
replaceFragment(FragmentEditUsers())
}
CodePudding user response:
Directly working with Activity from the fragment is not a good practice, it will become a nest of bugs in the future))
The first option is SharedViewModel
which you can share between your activity and fragment. But maybe you don't want it if you have simple functionality and you don't want to involve ViewModel
here.
The second option, which usually was used before Fragment Result API
and SharedViewModel
were callbacks.
The third one which I prefer and it's way cleaner is Fragment Result API
.
You can find more information here -