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?
CodePudding user response:
At First, convert the type of list to the array list
private val fragments: ArrayList<Fragment>
Then you can add the fragment to the list
fun addFragment(Fragment fragment){
fragments.add(fragment);
}
the viewpager2 automatically manages the adding and removeing of the fragments
CodePudding user response:
Set off screen limit to the number of fragments you want to create on viewpager.
mViewPager.setOffscreenPageLimit(n); // number of fragments you want to create