之前分享过几个tab+viewPager的库。。这种东西开发中特别常见。今天抽空补一个viewPager的adapter。用来搭配使用
创建FragmentInstancePagerAdapter,如下:
mport androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter/*** 为每个类型 Fragment 都只出现一个的 ViewPager 准备的 Adapter** @author* @date*/
class FragmentInstancePagerAdapter(fm: FragmentManager
) : FragmentStatePagerAdapter(fm) {private val list = mutableListOf<AdapterFragmentPager<*>>()inline fun <reified T : Fragment> append(title: CharSequence?,noinline creator: () -> T) {append(T::class.java, title, creator)}/*** 追加一个Fragment* @param clazz Fragment类型的Class* @param title 标题* @param creator 创建该Fragment实例*/fun <T : Fragment> append(clazz: Class<T>,title: CharSequence?,creator: () -> T) {list.add(AdapterFragmentPager(clazz, title, creator))notifyDataSetChanged()}inline fun <reified T : Fragment> indexOfType(): Int {return indexOfType(T::class.java)}/*** 获取指定类型Fragment的下标*/fun <T : Fragment> indexOfType(clazz: Class<T>): Int {return list.indexOfFirst { it.clazz == clazz }}inline fun <reified T : Fragment> removeByType() {removeByType(T::class.java)}/*** 移除指定类型的Fragment*/fun <T : Fragment> removeByType(clazz: Class<T>) {list.removeAll { it.clazz == clazz }notifyDataSetChanged()}override fun getItem(position: Int): Fragment {return list[position].creator()}override fun getCount(): Int {return list.size}override fun getPageTitle(position: Int): CharSequence? {return list[position].title}override fun getItemPosition(pageFragment: Any): Int {return list.indexOfFirst {it.clazz.isInstance(pageFragment)}}private class AdapterFragmentPager<T : Fragment>(val clazz: Class<T>,val title: CharSequence?,val creator: () -> T)
}
END