按照这个不错的教程https://medium.com/@eijaz/getting-started-with-tablayout-in-android-kotlin-bb7e21783761
,我有一个项目正在使用viewPager使用tablayout我遇到的问题是,实例化视图/片段后,视图中将不再发生任何事情。它们确实是静态的。我想用从服务器检索到的数据填充回收者视图。不是一次,不是两次,而是用户每次按下某些选项卡。
我试图寻找答案,但是我没有运气。也许带有片段的viewPager初始化后不应该更改?
-MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentAdapter = MyPagerAdapter(supportFragmentManager)
viewpager_main.adapter = fragmentAdapter
mainTabbedLayout.setupWithViewPager(viewpager_main)
}
}
-MyPagerAdapter.kt
class MyPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
val fragmentList = listOf<Fragment>(ListFragment(), ScanFragment(), MinFragment(), SettingsFragment())
override fun getItem(position: Int): Fragment {
when (position) {
0 -> {
Log.d("Fragment", "Position: $position")
return fragmentList[position]
}
1 -> {
Log.d("Fragment", "Position: $position")
return fragmentList[position]
}
2 -> {
Log.d("Fragment", "Position: $position")
return fragmentList[position]
}
3 -> {
Log.d("Fragment", "Position: $position")
return fragmentList[position]
}
else -> {
throw IllegalArgumentException()
}
}
}
override fun getCount(): Int {
return fragmentList.count()
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> "Liste"
1 -> "Scan"
2 -> "Min"
3 -> "Settings"
else -> {
throw IllegalArgumentException()
}
}
}
}
-ListFragment.kt
class ListFragment : Fragment() {
val TAG = "ListFragment"
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.list_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated")
}
}
在MyPagerAdapter.kt中,如果将标签页按得足够远,则设置FragmentStatePagerAdapter(而不是FragmentPagerAdapter)会使视图重新加载,但这还不够。我已经制作了要在iOS中创建的应用程序,在该应用程序中,以选项卡式布局访问时总是会触发特殊功能。在这种情况下不可能吗?
有什么办法可以强制进行新的初始化?