简体   繁体   English

Android中NavController的理解题

[英]Comprehension question about the NavController in Android

I just started to use the Jetpack Navigation in Android and I have a question.我刚开始在 Android 中使用 Jetpack Navigation,我有一个问题。 I have the following method inside a Fragment that implements View.OnClickListener我在实现 View.OnClickListener 的 Fragment 中有以下方法

public void onClick(View view) {

    if(view.getId() == R.id.imageButton_Softdrinks_en) {

        int amount = 1;
        Menu_FragmentDirections.ActionMenuFragmentToSoftdrinks action = Menu_FragmentDirections
                .actionMenuFragmentToSoftdrinks(amount);

        Navigation.findNavController(view).navigate(action);



    }

}

Basically the method works but I do not really comprehend why.基本上该方法有效,但我不明白为什么。 The View in the method declaration are supposed to be ImageButtons.方法声明中的 View 应该是 ImageButtons。 When using the command:"Navigation.findNavController(view)" Android searches for the Navcontroller of the view.使用命令时:"Navigation.findNavController(view)" Android 搜索视图的 Navcontroller。 Given that the view is an ImageButtom I do not understand why the navigation works.鉴于该视图是 ImageButtom 我不明白为什么导航有效。 The ImageButtoms do not have a NavController or a NavHost. ImageButtom 没有 NavController 或 NavHost。 Would anyone mind explaining this to me.有没有人介意向我解释一下。 I'd appreciate every comment and would be quite thankful for your help.我会感谢每一条评论,并非常感谢您的帮助。

You can call Navigation.findNavController(View) on any View in the View hierarchy.您可以在View层次结构中的任何View上调用Navigation.findNavController(View) The system will then traverse up the hierarchy until it finds the parent Fragment (the NavHostFragment ), and then it will find the NavController of the NavHostFragment .然后系统将向上遍历层次结构,直到找到父FragmentNavHostFragment ),然后它会找到 NavHostFragment 的NavHostFragment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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