天天看點

安卓中使用ViewPager2實作上下滑動翻頁

目标

實作上下滑動翻頁,類似于抖音、快手短視訊的操作方式.

實作方案

  • 添加依賴
implementation "androidx.viewpager2:viewpager2:1.0.0"
      
  • 布局檔案:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<androidx.viewpager2.widget.ViewPager2
android:id="@+id/vp2"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>
      
  • 擴充卡
class MyAdapter(fragmentActivity: FragmentActivity, private val fragments: ArrayList<Fragment>) :
    FragmentStateAdapter(fragmentActivity) {
    override fun createFragment(position: Int) = fragments[position]

    override fun getItemCount() = fragments.size
}
      
  • Fragment
class Fragment1 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val tv = TextView(context)
        tv.text = "第一頁"
        tv.setBackgroundColor(Color.parseColor("#f7acbc"))
        tv.gravity = Gravity.CENTER
        return tv
    }
}
class Fragment2 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val tv = TextView(context)
        tv.text = "第二頁"
        tv.setBackgroundColor(Color.parseColor("#9b95c9"))
        tv.gravity = Gravity.CENTER
        return tv
    }
}
      
  • 調用
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val vp2 = findViewById<View>(R.id.vp2) as ViewPager2
        val fragment1 = Fragment1()
        val fragment2 = Fragment2()
        val fragments = ArrayList<Fragment>()
        fragments.add(fragment1)
        fragments.add(fragment2)
        //設定上下滑動
        vp2.orientation = ViewPager2.ORIENTATION_VERTICAL
        vp2.adapter = MyAdapter(this, fragments)
    }
}