ViewPager Adapter 显示错误的图像

ViewPager Adapter shows wrong image

我有带图片的回收视图。当我 select 图像时,打开 viewpager 图像滑块。但它总是显示第一张图片,即使我点击另一张图片。

我试图将 recyclerview 的位置发送到 ImageSliderAdapter 中的 instantiateItem() imageView.setImageResource(imageModelArrayList[position]) 但它引发了 IndexOutOfBoundException。

这是我的 ImageSliderAdapter 代码

    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
    }
} 

这里是适配器初始化

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 }

您需要致电setCurrentItem。这会将寻呼机滚动到正确的项目。