viewpage2本身自带了懒加载模式,十分人性化。
class TabLayoutActivity : AppCompatActivity() {
private lateinit var mPagerAdapter: TabPagerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tablayout)
mPagerAdapter = TabPagerAdapter(this)
initTab()
// initOther()
}
private fun initOther(){
val joinStr1 = arrayOf("a","b","c","d").joinToString(
separator = "",prefix = "前缀",postfix = "后缀",limit = 3,truncated = "····"
).apply {
print(this)
}
}
private fun initTab() {
val titles = arrayListOf(
"精选",
"体育",
"巴萨",
"购物",
"明星",
"视频",
"健康",
"励志",
"图文",
"本地",
"动漫",
"搞笑",
"舞蹈",
"其他"
)
val fragments = ArrayList<Fragment>()
titles.indices.map { i->
fragments.add(TestFragment())
}
mPagerAdapter.setNewFragments(fragments)
viewpager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
viewpager.adapter = mPagerAdapter
TabLayoutMediator(
tabs, viewpager,
TabLayoutMediator.TabConfigurationStrategy { tab, position -> tab.text = titles[position] }
).attach()
viewpager.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){
})
}
class TestFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_item_one, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tv_item.text = javaClass.name
tv_item.background = ContextCompat.getDrawable(requireContext(), R.mipmap.bianpao)
}
}
class TabPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
private val mFragmentList = ArrayList<Fragment>()
fun setNewFragments(data: ArrayList<Fragment>) {
if (data.isNotEmpty()) {
mFragmentList.clear()
mFragmentList.addAll(data)
notifyDataSetChanged()
}
}
fun removeFragment(position: Int) {
if (mFragmentList.size > position) {
mFragmentList.remove(mFragmentList[position])
notifyDataSetChanged()
}
}
override fun getItemCount(): Int {
return mFragmentList.size
}
override fun createFragment(position: Int): Fragment {
return mFragmentList[position]
}
}