应用程序运行时,如何创建ViewPager2的所有片段?
我的主动脉包含ViewPager2。
ViewPager2管理了4个片段(家庭范围,字典范围,上传段,社区范围)。
我的ViewPagerAdapter:
inner class ViewPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
private val fragments: List<Fragment> =
listOf(HomeFragment(), DictionaryFragment(), UploadFragment(), CommunityFragment())
private var viewList = arrayOf(
layoutInflater.inflate(R.layout.fragment_home, null),
layoutInflater.inflate(R.layout.fragment_dictionary, null),
layoutInflater.inflate(R.layout.fragment_upload, null),
layoutInflater.inflate(R.layout.fragment_community, null),
)
override fun getItemCount() = viewList.size
override fun createFragment(position: Int): Fragment = fragments[position]
}
我想在主要活动中执行字典片段的功能。
因此,我尝试了supportFragmentManager.findfragmentbytag(“ f1”)作为字典范围).myfunction()
。
但是,此代码会引发NullPoInterException。
我的猜测是因为尚未创建字典片段。
应用程序运行时,如何创建ViewPager2的所有片段?
My MainActivity contains viewpager2.
And the viewpager2 manages 4 fragments(HomeFragment, DictionaryFragment, UploadFragment, CommunityFragment).
My ViewPagerAdapter:
inner class ViewPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
private val fragments: List<Fragment> =
listOf(HomeFragment(), DictionaryFragment(), UploadFragment(), CommunityFragment())
private var viewList = arrayOf(
layoutInflater.inflate(R.layout.fragment_home, null),
layoutInflater.inflate(R.layout.fragment_dictionary, null),
layoutInflater.inflate(R.layout.fragment_upload, null),
layoutInflater.inflate(R.layout.fragment_community, null),
)
override fun getItemCount() = viewList.size
override fun createFragment(position: Int): Fragment = fragments[position]
}
I want to execute the function of the Dictionary fragment in the main activity.
So I tried supportFragmentManager.findFragmentByTag("f1") as DictionaryFragment).myFunction()
.
However, this code throws a NullPointerException.
My guess is that it's because the Dictionary fragment hasn't been created yet.
How can I create all the fragments of viewpager2 when the app runs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将屏幕限制设置为您要在ViewPager上创建的片段数量。
Set off screen limit to the number of fragments you want to create on viewpager.
首先,将列表类型转换为数组列表
,然后您可以将片段添加到列表中
viewPager2自动管理片段的添加和删除
At First, convert the type of list to the array list
Then you can add the fragment to the list
the viewpager2 automatically manages the adding and removeing of the fragments