简体   繁体   中英

Why navigation still error after passing the necessary parameter?

I have 3 fragments (A,B,C), the flow is like this: A -> B <-> C . I want fragment B only receive argument from fragment C, but I got error on Fragment A that says I have to pass an argument when navigate from fragment A to B. So to avoid that error, I pass 0 (ie the argument type is integer).

But even after I pass 0, I still get error on the line code that will navigate me from fragment A to B.

Here is my fragment B:

private val args: GameFragmentArgs by navArgs()
private var questionIndex = args.getQuestionIndexFromGameOverFragment

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {       
        val binding = DataBindingUtil.inflate<FragmentGameBinding>(
                inflater, R.layout.fragment_game, container, false)               
        binding.game = this   
        timer(binding)        

    return binding.root
}

I don't know why it gets error and how can I fix it?

Here's the problem:

private var questionIndex = args.getQuestionIndexFromGameOverFragment

You call the arguments too early, they're not there yet. The solution would be to delay assigning the questionIndex value, for example with lazy :

private val questionIndex by lazy { args.getQuestionIndexFromGameOverFragment }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM