kotlinandroid-viewpagerpositionandroidimageslider

ViewPager Adapter shows wrong image


I have recycler view with images. When I select the image, opens the viewpager image slider. But it always shows the first image even though I click on another.

I have tried to send the recyclerview's position to instantiateItem()in ImageSliderAdapter imageView.setImageResource(imageModelArrayList[position]) but it made IndexOutOfBoundException.

Here is my ImageSliderAdapter code

    PagerAdapter() {
    private val inflater: LayoutInflater = LayoutInflater.from(context)


    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val imageLayout = inflater.inflate(R.layout.sliding_image, container, false)!!


        val imageView = imageLayout
            .findViewById(R.id.imageDetail) as ImageView

        imageView.setImageResource(imageModelArrayList[position])


        container.addView(imageLayout, 0)

        return imageLayout
    }


    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    override fun saveState(): Parcelable? {
        return null
    }
} 

Here is adapter initialization

private fun initSliderAdapter() {

        mPager = findViewById(R.id.pager)
        mPager!!.adapter =
            ImageSliderAdapter(this@ImageDetailActivity, imageModelArrayList!!)

        val indicator = findViewById<CirclePageIndicator>(R.id.indicator)

        indicator.setViewPager(mPager)

        val density = resources.displayMetrics.density

        //Set circle indicator radius
        indicator.radius = 5 * density

        NUM_PAGES = imageModelArrayList!!.size


             indicator.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageSelected(position: Int) {
                currentPage = position

            }
            override fun onPageScrolled(pos: Int, arg1: Float, arg2: Int) {

            }
            override fun onPageScrollStateChanged(pos: Int) {

            }
        })
    }
 companion object  {

        private var mPager: ViewPager? = null
        private var currentPage = 0
        private var NUM_PAGES = 0 }

Solution

  • You need to call setCurrentItem. This will scroll the pager to the correct item.