我正在使用ViewPager2
,并且我有一个按钮,可以将其当前页面更改为第二页,如下所示:
button_next.setOnClickListener {
setup_view_pager.currentItem = 1
}
它一直有效,直到手动滑动页面,然后抛出此错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: rs.ac.bg.matf.risk.matfasistent, PID: 32028
java.lang.IllegalStateException: Expected position values between -1 and 1.
at androidx.core.util.Preconditions.checkState(Preconditions.java:96)
at androidx.viewpager2.widget.MarginPageTransformer.transformPage(MarginPageTransformer.java:56)
at androidx.viewpager2.widget.PageTransformerAdapter.onPageScrolled(PageTransformerAdapter.java:72)
at androidx.viewpager2.widget.CompositeOnPageChangeCallback.onPageScrolled(CompositeOnPageChangeCallback.java:59)
at androidx.viewpager2.widget.ScrollEventAdapter.dispatchScrolled(ScrollEventAdapter.java:407)
at androidx.viewpager2.widget.ScrollEventAdapter.onScrolled(ScrollEventAdapter.java:188)
at androidx.recyclerview.widget.RecyclerView.dispatchOnScrolled(RecyclerView.java:5100)
at androidx.recyclerview.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:5265)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1012)
at android.view.Choreographer.doCallbacks(Choreographer.java:824)
at android.view.Choreographer.doFrame(Choreographer.java:756)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:998)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6745)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
这只发生在这些点击上,当手动滑动碎片时一切正常。错误跟踪的所有位置都没有指向我的代码:(
这是我的 ViewPager 适配器:
class SetupAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle)
: FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount() = 3
override fun createFragment(position: Int): Fragment {
return when (position) {
0, 1, 2 -> StudentSelectionFragment()
else -> throw IllegalStateException()
}
}
}
这是Activity的全部相关代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val adapter = SetupAdapter(supportFragmentManager, lifecycle)
setup_view_pager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
setup_view_pager.adapter = adapter
setup_view_pager.setPageTransformer(MarginPageTransformer(1500))
button_next.setOnClickListener {
setup_view_pager.setCurrentItem(1, true)
}
}