我有ViewLager的TabLayout
点击关闭按钮,我尝试删除标签
closeIcon.setOnClickListener {
tabLayout.removeTabAt(pos)
fragments.removeAt(pos)
fragmentsTitle.removeAt(pos)
notifyDataSetChanged()
}
适配器代码:
class ViewPagerAdapter(fm: FragmentManager, private val tabLayout: TabLayout,
private val ctx: Context) : FragmentStatePagerAdapter(fm) {
private val fragments = ArrayList<FileFragment>()
private val fragmentsTitle = ArrayList<String>()
override fun getItem(position: Int): FileFragment = fragments[position]
override fun getCount(): Int = fragments.count()
override fun getPageTitle(position: Int): CharSequence = fragmentsTitle[position]
fun addFragment(fragment: FileFragment, title: String) {
fragments.add(fragment)
fragmentsTitle.add(title)
}
}
在MainActivity设置中ViewPager:
private fun setupViewPager(viewPager: ViewPager, tabLayout: TabLayout,
fragmentManager: FragmentManager, ctx: Context): ViewPagerAdapter {
val adapter = ViewPagerAdapter(fragmentManager, tabLayout, ctx)
viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewPager)
return adapter
}
但是当我删除标签时,我的片段不会被删除。我也可以滚动到上一个片段
答案 0 :(得分:0)
通过覆盖getItemPosition()
override fun getItemPosition(obj: Any): Int {
return PagerAdapter.POSITION_NONE
}