ViewPager结合Fragment和PagerAdapter

作者: 蓝不蓝编程 | 来源:发表于2019-08-07 09:59 被阅读12次

    简介

    本文一共包含四种样例:

    1. withFragment
      ViewPager结合Fragment.
    2. withFragmentAsView
      ViewPager结合Fragment并封装成View.
    3. withPagerAdapter
      ViewPager结合PagerAdapter.
    4. 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
            }
        }
    }
    
    

    完整源代码

    https://github.com/cxyzy1/viewPagerDemos.git

    相关文章

      网友评论

        本文标题:ViewPager结合Fragment和PagerAdapter

        本文链接:https://www.haomeiwen.com/subject/revndctx.html