简介
本文一共包含四种样例:
- withFragment
ViewPager结合Fragment. - withFragmentAsView
ViewPager结合Fragment并封装成View. - withPagerAdapter
ViewPager结合PagerAdapter. - withPagerAdapterAsView
ViewPager结合PagerAdapter并封装成View.
效果图
部分源代码展示
完整源代码见git
ViewPager结合Fragment的部分源代码:
- MainActivity.kt
class MainActivity : AppCompatActivity() {
private val pageTitles = arrayOf("Page 1", "Page 2", "Page 3", "Page 4", "Page 5")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragments = getFragments()
viewPager.adapter = object : FragmentStatePagerAdapter(supportFragmentManager) {
override fun getCount(): Int {
return fragments.size
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
}
}
private fun getFragments(): ArrayList<Fragment> {
val fragments = ArrayList<Fragment>()
for (index in 0 until pageTitles.size) {
val fragment = ViewPagerFragment.buildIntent(pageTitles[index])
fragments.add(fragment)
}
return fragments
}
}
- ViewPagerFragment.kt
class ViewPagerFragment : Fragment() {
private var title: String? = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = arguments?.getString(EXTRA_TITLE)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = View.inflate(context, R.layout.fragment_view_pager, null)
view.findViewById<TextView>(R.id.textView).text = title
return view
}
companion object {
private const val EXTRA_TITLE = "title"
fun buildIntent(title: String): ViewPagerFragment {
val fragment = ViewPagerFragment()
var bundle = Bundle()
bundle.putString(EXTRA_TITLE, title)
fragment.arguments = bundle
return fragment
}
}
}
网友评论