动态选项卡是指在Android应用中可以根据数据或用户交互动态添加、删除或修改的标签页(Tab)及其内容。与静态选项卡不同,动态选项卡的内容和数量可以在运行时改变,提供了更灵活的用户界面。
这是目前最推荐的实现方式:
// 在Activity/Fragment中
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
val viewPager = findViewById<ViewPager2>(R.id.view_pager)
// 创建适配器
val adapter = ViewPagerAdapter(this)
viewPager.adapter = adapter
// 绑定TabLayout和ViewPager
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = "Tab ${position + 1}"
}.attach()
// 添加新选项卡
fun addTab(title: String, fragment: Fragment) {
adapter.addFragment(fragment, title)
adapter.notifyDataSetChanged()
tabLayout.getTabAt(adapter.itemCount - 1)?.text = title
}
// 删除选项卡
fun removeTab(position: Int) {
adapter.removeFragment(position)
adapter.notifyDataSetChanged()
}
class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
private val fragments = mutableListOf<Fragment>()
private val titles = mutableListOf<String>()
fun addFragment(fragment: Fragment, title: String) {
fragments.add(fragment)
titles.add(title)
}
fun removeFragment(position: Int) {
if (position < fragments.size) {
fragments.removeAt(position)
titles.removeAt(position)
}
}
override fun getItemCount(): Int = fragments.size
override fun createFragment(position: Int): Fragment = fragments[position]
fun getTitle(position: Int): String = titles[position]
}
原因:Fragment没有被正确重建或数据没有刷新
解决:确保在适配器中正确实现createFragment
,并在数据变化时调用notifyDataSetChanged
原因:TabLayoutMediator没有正确同步
解决:在修改数据后重新绑定或使用TabLayoutMediator
的detach()
和attach()
原因:Fragment过于复杂或主线程执行耗时操作 解决:优化Fragment布局,使用异步加载数据
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
val customView = LayoutInflater.from(context).inflate(R.layout.custom_tab, null)
customView.tabText.text = adapter.getTitle(position)
tab.customView = customView
}.attach()
tab.icon = ContextCompat.getDrawable(context, if (hasNewContent) R.drawable.ic_new else R.drawable.ic_normal)
override fun onResume() {
super.onResume()
if (isVisibleToUser) {
loadData()
}
}
通过以上方法,可以实现功能强大且用户友好的动态选项卡界面。
没有搜到相关的文章