I want to make changes in my Layout that contains ViewPager2 according to the position of ViewPager2. Example -> I want to make a Button Visible when the ViewPager2 has the last item or position. But I am Not able to do so, Any Help and Suggestions would be Very Helpful Thank You.
My Adapter :
open class ImagesliderAdapter(private val context: Context, private val list: ArrayList<HomePageSlideEntity>, private val viewPager2: ViewPager2): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_imageslider, parent, false))
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val model = list[position]
if(position==list.size-1) {
viewPager2.post(runnable)
}
if(holder is MyViewHolder) {
holder.itemView.findViewById<ImageView>(R.id.ivimageslider).setImageURI(Uri.parse(model.image))
}
}
override fun getItemCount(): Int {
return list.size
}
private val runnable = Runnable {
list.addAll(list)
notifyDataSetChanged()
}
private class MyViewHolder(view: View): RecyclerView.ViewHolder(view)
}
CodePudding user response:
Use registerOnPageChangeCallback
in your ViewPager2
.
binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
Log.d("Page", "onPageScrolled: $position")
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
Log.d("Page", "onPageSelected: $position")
// use position and do what ever you want
//for 1st page
if (position <= 0) {
btn.visibility = View.GONE
} else {
btn.visibility = View.VISIBLE
}
//for last page
if (position 1 >= args.content.items.size) {
btn.visibility = View.GONE
} else {
btn.visibility = View.VISIBLE
}
}
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
}
})
CodePudding user response:
You are using RecyclerView.ViewHolder instead of MyViewHolder in your adapter. Replace RecyclerView.ViewHolder with MyViewHolder and it should work properly then.