从Android ViewPager2儿童片段导航到另一个片段

发布于 2025-01-21 00:49:21 字数 489 浏览 0 评论 0原文

有没有办法从ViewPager2的孩子碎片到另一个碎片? 假设我有一个父片[parent fragment]仅包含viewPager2和ablayout。我有2个孩子的碎片[Childragment1和Childragment2]由FragmentStateDapter创建。我想从Childrenfragment2导航到另一个FragmentB,以便当我从FragmentB导航时,以显示父母段落到Childfragment2的位置?

例如:ChildFragment1-> ChildFragment2-> fragmentb-> childragment2

我得到:

java.lang.IllegalArgumentException: Navigation action/destination id:actionChildFragment2_to_FragmentB cannot be found from the current destination

Is there a way to navigate from a child fragment of ViewPager2 to another fragment?
Let's say I have a parent fragment [ParentFragment] containing only a ViewPager2 and a TabLayout. I have 2 children fragments [ChildrenFragment1 and ChildrenFragment2] created with FragmentStateAdapter. I want to navigate from ChildrenFragment2 to another FragmentB so that when i navigate back from FragmentB, to show position of the ParentFragment to ChildFragment2?

ex: ChildFragment1 -> ChildFragment2 -> FragmentB -> ChildFragment2

I get:

java.lang.IllegalArgumentException: Navigation action/destination id:actionChildFragment2_to_FragmentB cannot be found from the current destination

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一杆小烟枪 2025-01-28 00:49:21

我找到了一个解决方案,将当前页面保留在ViewModel Livedata属性中,将其设置在ParentFragment内部的页面上:

binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(page: Int) {
            viewModel.updatePageSelected(page)
        }
    })

并观察ParentFragment内部的页面更改:

subscribeToLiveData(viewModel.viewPagerSelected) { page ->
        binding.viewPager.setCurrentItem(page, false)
    }

ParentViewModel:

private val _viewPagerSelected = MutableLiveData<Int>()
val viewPagerSelected: LiveData<Int> = _viewPagerSelected

fun updatePageSelected(newSelection: Int) {
    _viewPagerSelected.value = newSelection
}

I found a solution, i keep the current page in a ViewModel LiveData property, setting it on page change inside the ParentFragment:

binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(page: Int) {
            viewModel.updatePageSelected(page)
        }
    })

and observe the page change inside the ParentFragment:

subscribeToLiveData(viewModel.viewPagerSelected) { page ->
        binding.viewPager.setCurrentItem(page, false)
    }

The ParentViewModel:

private val _viewPagerSelected = MutableLiveData<Int>()
val viewPagerSelected: LiveData<Int> = _viewPagerSelected

fun updatePageSelected(newSelection: Int) {
    _viewPagerSelected.value = newSelection
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文