Android ViewPager实现
MainActivity
class MainActivity : AppCompatActivity() {
private val viewList = ArrayList<View>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
val adapter = MyViewPagerAdapter(viewList)
ViewPager1.adapter = adapter
}
private fun init() {
val view1 = View(this)
view1.setBackgroundColor(Color.RED)
val view2 = View(this)
view2.setBackgroundColor(Color.GREEN)
val view3 = View(this)
view3.setBackgroundColor(Color.BLACK)
viewList.add(view1)
viewList.add(view2)
viewList.add(view3)
}
}
MyViewPagerAdapter
class MyViewPagerAdapter(private val mList:ArrayList<View>): PagerAdapter() {
// 来判断显示的是否是同一张图片,这里我们将两个参数相比较返回即可
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
// 获取要滑动的控件的数量
override fun getCount(): Int {
return mList.size
}
// 如果有3张图片,滑动超出的部分会销毁
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(mList.get(position))
}
// 当要显示的图片可以进行缓存的时候,会调用这个方法进行显示图片的初始化,我们将要显示的ImageView加入到ViewGroup中,然后作为返回值返回即可
override fun instantiateItem(container: ViewGroup, position: Int): Any {
container.addView(mList.get(position))
return mList.get(position)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="@+id/ViewPager1"
android:layout_width="match_parent"
android:layout_height="250dp">
</androidx.viewpager.widget.ViewPager>
</LinearLayout>