我在片段上使用TabLayout时遇到问题。它只是通过显示另一个片段来执行,但是在我单击其他应用程序部分然后返回到包含TabLayout的片段之后,则不显示TabLayout内容。
My TabLayout Problem Ilustrate
class favoriteFragment:Fragment(){
private var tabLayout: TabLayout? = null
private var viewPager: ViewPager? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_favorites, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
tabLayout = view.findViewById(R.id.tabs) as TabLayout
viewPager = view.findViewById(R.id.viewpager) as ViewPager
super.onViewCreated(view, savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
viewPager!!.setAdapter(MyAdapter(fragmentManager))
tabLayout!!.post(Runnable { tabLayout!!.setupWithViewPager(viewPager) })
super.onActivityCreated(savedInstanceState)
}
private inner class MyAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm!!, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
private val int_items = 2
override fun getItem(position: Int): Fragment {
var fragment: Fragment? = null
when (position) {
0 -> fragment = MoviesFavoritesFragment()
1 -> fragment = TvSeriesFavoritesFragment()
}
return fragment!!
}
override fun getCount(): Int {
return int_items
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return "Movie Favorites"
1 -> return "Tv Series Favorites"
}
return null
}
}
}
这里是我的XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/material_blue_grey_800"
app:tabGravity="fill"
app:tabIndicatorColor="@color/colorPrimary"
app:tabSelectedTextColor="@color/white"
app:tabTextColor="@color/colorPrimary"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/tabs"/>
</androidx.constraintlayout.widget.ConstraintLayout>
最有可能的错误是在这里:
viewPager!!.setAdapter(MyAdapter(fragmentManager))
尝试在此处传递childFragmentManager