Home > Software engineering >  how can i add counter to viewpager2
how can i add counter to viewpager2

Time:01-01

image

I couldn't find how to do the counter algorithm

here is the adapter i wrote for my viewpager

class ViewPagerAdapter(val images : List,val mContext: Context) : RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolderClass>() {

inner class ViewPagerViewHolderClass(view: View) : RecyclerView.ViewHolder(view){
    val viewPagerFoto : ImageView
    init {
        viewPagerFoto = view.findViewById(R.id.viewPagerFoto)
    }
}


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerViewHolderClass {
    val view = LayoutInflater.from(mContext).inflate(R.layout.item_view_pager,parent,false)
    return ViewPagerViewHolderClass(view)
}

override fun onBindViewHolder(holder: ViewPagerViewHolderClass, position: Int) {
    val image = images[position]
    holder.viewPagerFoto.setImageResource(image)
}

override fun getItemCount(): Int {
    return images.size
}

}

My home Fragment

I am performing operations on homefragment

class HomeFragment : Fragment() {

    private lateinit var _binding : FragmentHomeBinding
    
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentHomeBinding.inflate(inflater,container,false)
        
        val images = listOf(
            R.drawable.f1,
            R.drawable.f2,
            R.drawable.f3,
            R.drawable.f4,
            R.drawable.f5,
            R.drawable.f6,
        )
        val adapter by lazy { ViewPagerAdapter(images,requireContext()) }
        _binding.viewPager.adapter = adapter


        
        return _binding.root
    }




}

CodePudding user response:

In onBindViewHolder method you have position parameter. You can pass it to viewHolder and use it

CodePudding user response:

    override fun onBindViewHolder(holder: ViewPagerViewHolderClass, position: Int) {
        val image = images[position]
        holder.viewPagerFoto.setImageResource(image)
    }

You can use position parameter, if you want just use it on there. But i suggest that use it on ViewPagerViewHolderClass with declaring new parameter named position and pass it over there.

  • Related