先在fragment或者activity中放置一个viewpager2
?然后在创建一个fragmentstateAdapter的子类? 重写里面的 createFragment()、getItemCount()、containsItem()和getItemId()四个方法
class DemoCollectionAdapter(fragment: Fragment,val fragmentlist:List<Fragment>) : FragmentStateAdapter(fragment) {//fragment 也可以换为 activity
private val fid2 = 222L
private val fid3 = 333L
private val ids = arrayListOf(fid2,fid3)
private val creatID= hashSetOf<Long>()
override fun getItemCount(): Int {
return fragmentlist.size
}
override fun createFragment(position: Int): Fragment {
val id = ids[position]
creatID.add(id)
val fragment = fragmentlist[position]
fragment.arguments = Bundle().apply {
putInt(ARG_OBJECT,position+1)
}
return fragment
}//返回需要创建的fragment
override fun containsItem(itemId: Long): Boolean {
return creatID.contains(itemId)
}//判断是否包含创建的ID(解决fragment数据为动态时无法刷新的问题)
override fun getItemId(position: Int): Long {
return position.toLong()
}
}
然后在ViewPager2所在的类进行适配器的实例化等
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list.add(Fragment2())
list.add(Fragment3())
val tabLayout = view.findViewById<TabLayout>(R.id.tab_layout)
viewPager = view.findViewById(R.id.pager)
TabLayoutMediator(tabLayout,viewPager){ tab,position ->
tab.text = "osjaod${position+1}"//创建和fragment一起滑动的Tab
}.attach()
demoCollectionAdapter = DemoCollectionAdapter(this,list)
viewPager.adapter = demoCollectionAdapter
}
和使用一般的适配器一样
补充,可以使用TabLayout添加一个可以和fragment一起滑动的Tab
?
?最终效果
?
|