我想将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()
}
}
}
})
}