Viewpager2 Android : 视图上的下一步按钮会向右生成两张幻灯片

Viewpager2 Android : A Next button on the view generates two slides to the right

我在 Android 上遇到了 viewpager2 问题。 我有一个 viewpager2 根据位置创建一些片段。每个片段都有一个下一个按钮,用于在视图分页器中水平导航。

但是当我从按钮请求下一页时,我有滑动两次的动作。它就像适配器的方法 createFragment 被调用了两次,由于片段边界的预加载...

Activity 管理视图寻呼机的人:

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
        }
    }
}

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)
   }
...
}

这样试试:-

  • 首先将 viewPager 变量 private 更改为 Activity 中的 public 就像删除 private 关键字一样。

    var viewPager : ViewPager2? = null

  • 在片段中改变setOnClickListener方法如下:

    view.button_continue.setOnClickListener { instance!!.viewPager!!.arrowScroll(View.FOCUS_RIGHT) }

*建议:

  • 在片段中,我们可以获得父activity实例并使用这种方式而不是将activity实例传递给每个片段。

    val instance = ((activity as AppCompatActivity) as ConfigurationActivity)