简体   繁体   English

使用 jetpack 从 ViewPager2 导航到另一个片段

[英]Navigate from ViewPager2 to another fragment using jetpack

I have single activity, FragmentHome contains viewpager2.我有一个活动,FragmentHome 包含 viewpager2。 Inside of viewpager there is FirstFragment.在viewpager 里面有FirstFragment。

在此处输入图片说明

when I want to navigate from FirstFragment to SecondFragment which is not in viewpager2当我想从 FirstFragment 导航到不在 viewpager2 中的 SecondFragment 时

在此处输入图片说明

it throws它抛出

 java.lang.IllegalArgumentException: navigation destination com.example.mymessangerfcm:id/action_FirstFragment_to_SecondFragment is unknown to this NavController

Dear community how to handle such navigation, and why the exception is thrown?亲爱的社区如何处理这样的导航,为什么会抛出异常?

you should use the Global Action.您应该使用全局操作。 When you are inside the viewpager, actually you are in a different navigation.当您在 viewpager 中时,实际上您处于不同的导航中。 So, you should make your action as Global.所以,你应该把你的行动作为全球性的。 You can check the Global Action from official website :您可以从官方网站查看全球行动:

https://developer.android.com/guide/navigation/navigation-global-action https://developer.android.com/guide/navigation/navigation-global-action

After the making action as global, you can navigate like this;将动作设为全局后,您可以像这样导航;

findNavController().navigate(R.id.action_global_FirstFragment_to_SecondFragment)

Note: If you don't see global action after the doing it, rebuild your project.注意:如果执行后没有看到全局操作,请重建您的项目。

I got below IllegalStateException when calling Navigation.findNavController(view) with ViewPager2.使用 ViewPager2 调用 Navigation.findNavController(view) 时,我低于 IllegalStateException。 However, the same setup working fine with old ViewPager.但是,相同的设置在旧的 ViewPager 上运行良好。

    java.lang.IllegalStateException: View android.widget.LinearLayout does not have a NavController set

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

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