Android Kotlin Fragmentadapter

刚接触kotlin写安卓, 一脸懵逼, 连教程都没看就开搞了

直接上代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package ${package}.base

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter

/**
 * Fragment适配器, ViewPager用
 * @property fm FragmentManager
 * @property fragments MutableList<Fragment>
 * @property fragmentTitles MutableList<String>
 * @constructor
 */
class QJFragmentAdapter(val fm: FragmentManager) : FragmentPagerAdapter(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    var fragments: MutableList<Fragment> = ArrayList()
    var fragmentTitles: MutableList<String> = ArrayList()

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }
    fun addFragment(fragment: Fragment, title: String) {
        fragments.add(fragment)
        fragmentTitles.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragmentTitles[position]
    }
    override fun getCount(): Int = fragments.size
}

使用方式很简单

1
2
3
4
5
6
7
8
9
var adapter = QJFragmentAdapter(supportFragmentManager)
var makeLeaveFragment = MakeLeaveFragment()
var leaveListFragment = LeaveListFragment()

adapter.addFragment(MakeLeaveFragment(), makeLeaveFragment.title)
adapter.addFragment(LeaveListFragment(), leaveListFragment.title)

viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewPager)

可以简化的地方: 创建一个BaseFragment, 声明一个title的属性, 然后每个Fragment类都继承这个, 就可以改成 adapter.addFragment(MakeLeaveFragment()) 这样少一行代码了