我在recyclerview中使用vp2

        override fun convert(helper: BaseViewHolder, item: Tweet) {
            val medias = item.medium.split(",")
            if (!item.video) {
                helper.getView<View>(R.id.vp).show()
                helper.getView<View>(R.id.insdotview).show()
                helper.getView<View>(R.id.videoview).hide()
                val ad = TweetPhotoAdapter()
                val a = medias.toMutableList()
                ad.setNewData(a)
                val vp2= helper.getView<ViewPager2>(R.id.vp)
                vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        LogUtils.w(onPageSelected(position))
                        super.onPageSelected(position)
                    }
                })


如果我在运行convert()时添加vp2.registerOnPageChangeCallback,则出现StackOverflowError错误
像这样

java.lang.StackOverflowError: stack size 8MB
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivi.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)
        at FFActivity$UserTweetAdapter2$convert$1.onPageSelected(FFActivity.kt:149)


如果我不添加PageChangeCallback,似乎没有问题

最佳答案

更改为

   override fun convert(helper: BaseViewHolder, item: Tweet) {
            val medias = item.medium.split(",")
            if (!item.video) {
                helper.getView<View>(R.id.vp).show()
                helper.getView<View>(R.id.insdotview).show()
                helper.getView<View>(R.id.videoview).hide()
                val ad = TweetPhotoAdapter()
                val a = medias.toMutableList()
                ad.setNewData(a)
                val vp2= helper.getView<ViewPager2>(R.id.vp)
                vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        LogUtils.w(position) // this line
                        super.onPageSelected(position)
                    }
                })

10-06 01:34