目标
实现上下滑动翻页,类似于抖音、快手短视频的操作方式.
实现方案
- 添加依赖
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)
}
}