直接上代码,采用kotlin编写。 Activity 源码如下:
package com.canbot.u05.activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.canbot.u05.R
import com.canbot.u05.activity.Splash.CustomAdapter.ViewHolder
import kotlinx.android.synthetic.main.splash.*
class Splash : FragmentActivity() {
class Callback : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
Log.d(TAG, "onPageSelected $position")
}
override fun onPageScrollStateChanged(state: Int) {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash)
val names = arrayOf("1", "2", "3","4","5","6")
pager.adapter = CustomAdapter(names)
pager.registerOnPageChangeCallback(Callback())
}
class CustomAdapter(private val dataSet: Array<String>) : RecyclerView.Adapter<ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textView) as TextView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item2, parent, false)
return ViewHolder(view).also {
Log.d(TAG, "onCreateViewHolder $it")
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = dataSet[position]
Log.d(TAG, "onBindViewHolder: " + holder)
}
override fun getItemCount(): Int {
return dataSet.size
}
}
companion object {
val TAG = "Splash"
}
}
下面是 splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/pager"
android:background="#3F51B5"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
最后是 item2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00">
<TextView
android:id="@+id/textView"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:text="TextView" />
</RelativeLayout>
使用版本:
implementation "androidx.viewpager2:viewpager2:1.0.0"
|