安卓Kotlin 使用ViewPager2实现简易左右滑动翻页效果

布局很简单,R.layout.onepage仅有一个占满全屏幕的ImageView名为oneiR.layout.activity_view仅有一个占满全屏幕的ViewPager2名为vp
以下为Activity的全部代码:

class ViewActivity:Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view)
        vp.adapter = ViewData.RecyclerViewAdapter()
        vp.registerOnPageChangeCallback(object : OnPageChangeCallback(){})
    }
    class ViewData(itemView: View) : RecyclerView.ViewHolder(itemView) {
        class RecyclerViewAdapter: RecyclerView.Adapter<ViewData>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewData {
               return ViewData(LayoutInflater.from(parent.context).inflate(R.layout.onepage, parent, false))
            }
            override fun onBindViewHolder(holder: ViewData, position: Int) {
            	when(position){
            		0 -> holder.itemView.onei.setImageResource(R.drawable.img1)
            		1 -> holder.itemView.onei.setImageResource(R.drawable.img2)
            		2 -> holder.itemView.onei.setImageResource(R.drawable.img3)
            	}
            }
            override fun getItemCount(): Int {
                return 3
            }
        }
    }
}

你可能感兴趣的:(kotlin,安卓,viewpager,安卓,listview)