I use navArgs and also I have read that I should use old school bundle in my case. Android navArgs clear on back
I have the same issue as above:
I have fragment A that opens fragment B with navArgs, then I navigate to fragment C and the user presses back, so fragment B is opened with the same navArgs and I don't want that.
This is my Fragment A where I pass some data using args and I would like to pass one data using bundle to clear that after all.
class FragmentA : Fragment() {
private val args by navArgs<WorkItemsListFragmentArgs>()
[...]
val bundle = Bundle()
bundle.putBoolean("data", true)
val fragmentB = FragmentB()
fragmentB.arguments = bundle
fragmentManager?.beginTransaction()?.replace(R.id.main,fragmentB)?.commit()
// R.id.main is my main navigation layout
navArgs default library file
@MainThread
public inline fun <reified Args : NavArgs> Fragment.navArgs(): NavArgsLazy<Args> =
NavArgsLazy(Args::class) {
arguments ?: throw IllegalStateException("Fragment $this has null arguments")
}
fragmentB where I also use some data from safe navArgs
private val args by navArgs<FragmentB>()
val argsArguments = this.arguments
val inputData = argsArguments?.getBoolean("data")
// using some method then clear
argsArguments.clear()
My error regarding to this line where I would like to implement new FragmnetB Args
at com.android.fragments.reporting.FragmentB.getArgs(FragmentB.kt:59)
59 this line
private val args by navArgs<FragmentB>()
My suggestion is I somehow overwrite something in args and it doesn't work anymore. what is the solution for it?
EDIT1:
I have changed R.id.main to R.id.navHostFragment still the same error.
I think I understand my issue:
"Replace whatever is in the fragment_container view with this fragment, and add the transaction to the back stack"
when I use replace it clear the fragment_container so it clears all the args from navigation as I understand.
I could useadd, but it doesn't work as well.. still if you you have any suggestions how to handle it feel free to communicate :)
Thanks
EDIT2 regarding to comment:
fragmentA
if(isNavigated) {
findNavController().navigate(
FragmentADirections.actionFragmentAToFragmentB(
id = item.id,
isNavigated = isNavigated
)
)
fragmentB
var isNavigated = args.isNavigated
if (isNavigated) {
add(Type.TIME)
isNavigated = false
// args.isNavigated = false is impossible cuz immutable value
}
Ok my solution:
-> use sharedViewModel
-> use shared pref
-> use companion object (not efficient)
-> change state of element in recyclerview for example i.e. toNavigate
Thanks for answers if you have better idea please share.