以编程方式设置页面时未调用ViewPager onPageSelected

时间:2019-08-08 10:00:21

标签: android android-layout android-viewpager android-tablayout

我想将ViewPager与自定义适配器一起使用。但是我面临页面切换的问题。 OnPageSelected侦听器未返回正确的值/未响应页面选择。与使用tabLayout.getTabAt(0)?.select()viewPager.currentItem = 0相同。

我正在显示每个屏幕时显示键盘并请求焦点,这意味着我每次都需要ViewPager内正确的屏幕位置。当我的键盘有时消失或显示了不应显示的位置时,我发现了此问题。看起来onPageSelected有时也称为下一个屏幕,它将跟随当前屏幕。例如,如果我以编程方式切换到Screen1,即使Screen2在屏幕上可见,它也会在onPageSelected内返回Screen1 id。

val pageList: List<FlowScreen> = listOf(
            Screen1(app, this, viewPager, R.layout.screen_one),
            Screen2(app, this, viewPager, R.layout.screen_two),
            Screen3(app, this, viewPager, R.layout.screen_three),
            Screen4(app, this, viewPager, R.layout.screen_four),
        )

        pagerAdapter = CustomViewPagerAdapter(pageList)
        viewPager.adapter = pagerAdapter
        tabLayout.setupWithViewPager(viewPager)
        viewPager.currentItem = 0

        viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {}
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                when(pageList[position]){
                    is Screen1 -> {
                        app.hideKeyboard(viewPager)
                    }
                    is Screen2 -> {
                        (pageList[position] as Screen2).apply {
                            doSomeStuffInScreen()
                            requestFocusToEditText()
                        }
                    }
                    is Screen3 -> {
                        (pageList[position] as Screen3).apply {
                            app.showKeyboard()
                            requestFocusToEditText()
                        }
                    }
                    is Screen4 -> {
                        app.showKeyboard()
                    }
                }
            }
        })
    }

0 个答案:

没有答案