我在Android上遇到viewpager2问题。我有一个viewpager2根据位置创建一些片段。每个片段都有一个下一个按钮,可在视图寻呼机中水平导航。
但是当我从按钮要求下一页时,我有滑动两次的动作。由于片段边界的预加载,就像调用适配器的createFragment方法两次一样。 >
管理视图寻呼机的活动:
class ConfigurationActivity : AppCompatActivity() {
private var viewPager : ViewPager2? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_configuration)
viewPager = viewPager2
val instance = this
viewPager!!.apply {
isUserInputEnabled = true
orientation = ViewPager2.ORIENTATION_HORIZONTAL
if(viewPager!!.adapter == null)
viewPager!!.adapter = ConfigAdapter(supportFragmentManager, lifecycle, instance, 2)
}
viewPager!!.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
currentItem = position
}
})
}
companion object{
private var currentItem : Int = 0
fun nextPage(instance : ConfigurationActivity, currentPosition : Int?){
instance.viewPager!!.currentItem = currentItem + 1
}
}
}
The FragmentStateAdapter
class ConfigAdapter(fm: FragmentManager, lc : Lifecycle, private val instance : ConfigurationActivity, configSnapshot : ArrayList<Configuration>) : FragmentStateAdapter(fm, lc) {
private val configSize = configSnapshot.size
override fun getItemCount(): Int {
val length = configSize + 3
instance.pageIndicatorView.count = length
return length
}
override fun createFragment(position: Int): Fragment {
Timber.d("creating fragment at position $position")
return when(position){
0 -> WelcomeFragment(instance)
in 1..configSize /* position between 1 and configSize (included) */ -> ConfigureFragment(instance, position-1)
1 + configSize -> IdentifyFragment(instance)
2 + configSize -> EndFragment()
else -> Fragment()
}
}
}
一个片段示例:
class ConfigureFragment(private val instance : ConfigurationActivity, private val configPosition: Int) : Fragment() {
...
view.button_continue.setOnClickListener {
nextPage(instance, configPosition+1)
}
...
}
我在Android上遇到viewpager2问题。我有一个viewpager2根据位置创建一些片段。每个片段都有一个下一个按钮,可在视图寻呼机中水平导航。但是当...
以这种方式尝试:-