Android实现ViewPager适配器kotlin简单实现

Android实现ViewPager适配器kotlin

效果

在n个视图间水平滑动切换
注意是viewpager实现的,viewpager2的适配器和1不同

1.适配器类kotlin代码

类名:VPAdapter
属性:
layoutList整型列表,保存要切换的视图id
context上下文,即调用它的Activity
itemCount:页数,从1开始

override时记得把高亮的todo提示删掉

package com.xayah.gesturesdemo.activity.tiktok

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.viewpager.widget.PagerAdapter
import com.xayah.gesturesdemo.R

/*
    *name: GesturesDemo 
    *description:
    */
class VPAdapter() : PagerAdapter () {
    private lateinit var layoutList: IntArray
    private lateinit var context: Context
    private var itemCount = 1

    constructor(context: Context,itemCount:Int,layoutList:IntArray) : this(){
        this.context = context
        this.itemCount = itemCount
        this.layoutList = layoutList
    }
    override fun getCount(): Int {
        return this.itemCount
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view==`object`
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = View.inflate(context,this.layoutList[position],null)
        container.addView(view)
        return view
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        super.destroyItem(container, position, `object`)
    }
}

2.activity调用适配器

var layouts = intArrayOf(
        R.layout.activity_tiktok_view1,		
        R.layout.activity_tiktok_view2
    )
var viewPager = findViewById<ViewPager>(R.id.tiktok_viewpage)
viewPager.adapter = VPAdapter(this,2,layouts)

很简单吧

参考:
https://blog.csdn.net/whjk20/article/details/107338023

你可能感兴趣的:(AndroidStudio开发,kotlin,android,kotlin,开发语言)