在 Viewpager2 上的第 0 个位置添加项目后,该项目无法正确滚动/添加到视图,并在滚动后再次显示当前视图。将项目添加到第 0 个位置后,主要初始项目不可见。
我的
Viewpager's Adapter
看起来像下面这样。
inner class ScreenSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int {
return list.size
}
override fun createFragment(position: Int): Fragment = ScrollFragment(list[position])
fun addFragment(string: String) {
list.add(string)
notifyItemInserted(list.size)
}
fun addAtPreviousFragment(string: String) {
list.add(0, string)
notifyItemInserted(0)
}
}
addAtPreviousFragment
正在将视频添加到第0个位置。
ViewPager 在下一个添加项目,第 0 个位置如下所示
mAddAtNext.setOnClickListener {
Handler(Looper.getMainLooper()).postDelayed(
{
val randomNext = (50..90).random()
println("randomNext >>>>>> $randomNext")
pagerAdapter.addFragment("Next $randomNext")
}, 200
)
}
mAddAtPrevious.setOnClickListener {
Handler(Looper.getMainLooper()).postDelayed(
{
val randomPrevious = (0..40).random()
println("randomPrevious >>>>>> $randomPrevious")
pagerAdapter.addAtPreviousFragment("Previous $randomPrevious")
}, 200
)
}
相同的代码已添加到 Git Hub。
如有任何帮助,我们将不胜感激。预先感谢
您好,请尝试这个版本,我已经测试过并且工作正常
class MainActivity : AppCompatActivity() {
private lateinit var list: ArrayList<String>
private lateinit var pagerAdapter: ScreenSlidePagerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpViewPager()
}
fun setUpViewPager() {
list = arrayListOf()
list.add("45")
val mViewPager: ViewPager2 = findViewById(R.id.view_pager)
pagerAdapter = ScreenSlidePagerAdapter(this)
mViewPager.adapter = pagerAdapter
val mAddAtNext: AppCompatButton = findViewById(R.id.btn_next)
val mAddAtPrevious: AppCompatButton = findViewById(R.id.btn_previous)
pagerAdapter.submitInitialItem(list.first())
mAddAtNext.setOnClickListener {
val randomNext = (50..90).random()
println("randomNext >>>>>> $randomNext")
pagerAdapter.addFragment("Next $randomNext")
}
mAddAtPrevious.setOnClickListener {
val randomPrevious = (0..40).random()
println("randomPrevious >>>>>> $randomPrevious")
pagerAdapter.addAtPreviousFragment("Previous $randomPrevious")
}
}
inner class ScreenSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
private val fragmentList: MutableList<Fragment> = mutableListOf()
fun submitInitialItem(string: String) {
fragmentList.add(ScrollFragment(string))
}
override fun getItemCount(): Int {
return fragmentList.size
}
override fun createFragment(position: Int): Fragment = fragmentList[position]
fun addFragment(string: String) {
fragmentList.add(ScrollFragment(string))
notifyItemInserted(fragmentList.size)
}
fun addAtPreviousFragment(string: String) {
fragmentList.add(0, ScrollFragment(string))
notifyItemInserted(0)
}
override fun getItemId(position: Int): Long {
return fragmentList[position].hashCode().toLong()
}
override fun containsItem(itemId: Long): Boolean {
return fragmentList.any { it.hashCode().toLong() == itemId }
}
}
}