一. ViewPager2实现无限轮播
废话不多说直接上代码
1.初始化viewpger2
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/frag_shouye_vp2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/color_999999"></androidx.viewpager2.widget.ViewPager2>
1.添加viewpager适配器,viewpager2直接可使用RecyclerView.Adapter
class ShouYeVPagerAdaPter(context: Context):RecyclerView.Adapter<ShouYeVPagerAdaPter.ViewHodler>() {
private var bannerArr = intArrayOf()
private var context:Context? = null
init {
this.context = context
}
fun setData(bannerArr: IntArray){
this.bannerArr = bannerArr
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): ViewHodler {
return ViewHodler(
LayoutInflater.from(parent.context).inflate(
R.layout.shouye_vp_itme,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHodler, position: Int) {
if (bannerArr.isNotEmpty()){
holder.vp_itme_iv.setBackgroundResource(bannerArr[position%bannerArr.size])//此处是无限轮播的关键代码
}else{
holder.vp_itme_iv.setBackgroundResource(R.mipmap.meikuang_noe_bgc)
}
}
override fun getItemCount(): Int = Int.MAX_VALUE//设置最大int值是为了进行无线轮播
class ViewHodler(itemView: View) : RecyclerView.ViewHolder(itemView) {
var vp_itme_iv = itemView.vp_itme_iv
}
}
3.注册滑动监听
frag_shouye_vp2.registerOnPageChangeCallback(myOnPageChangeCallback)
注意需要在不需要的时候需要进行反注册
frag_shouye_vp2.unregisterOnPageChangeCallback(myOnPageChangeCallback)
private var myOnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int,
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
this@ShouYeFragment.position = position
if (bannerArr.isNotEmpty()){
//获取小圆点的位置
//偏移量的百分比+偏移量
leftMagin = (positionOffset * distance + position % bannerArr.size * distance)
Log.i("TAG", "onPageScrolled: $leftMagin")
rlParams.leftMargin = leftMagin.toInt()
dot_iv.layoutParams = rlParams
}
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
if (state == ViewPager2.SCROLL_STATE_IDLE) {
if (position == 0) {
} else {
}
} else {
}
}
}
3.创建handler,实现自动轮播
private var handler = object : Handler(Looper.getMainLooper()) {}
在 onResume进行第一次发送
override fun onResume() {
super.onResume()
handler.postDelayed(runnable, 5000)
}
在ruunable里面使用递归实现自动轮播
private var runnable: Runnable = object : Runnable {
override fun run() {
frag_shouye_vp2.currentItem = ++frag_shouye_vp2.currentItem//给viewpger设置显示
handler.postDelayed(this, 5000)//递归
}
}
``` 持续更新中
网友评论