Tablayout在Android Kotlin中的Fragment中不起作用

时间:2019-11-19 15:57:18

标签: android kotlin tabs fragment

我正在尝试在我的片段之一中添加制表符布局。

mainActivity中的tablayout效果很好,但是片段中的tablayout无效。

选项卡菜单显示良好,但是viewPager中没有任何显示。

I want to make like this. and it's my app

HomeDetailFragment.kt

class HomeDetailFragment : Fragment() {
lateinit var homeDetailRecyclerViewAdapter : HomeDetailRecyclerViewAdapter

private val myContext = FragmentActivity()

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_home_detail, container, false)

}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    configureTopNavigation()
}

private fun configureTopNavigation(){
    vp_home_detail.adapter = HomeDetailPagerAdapter(myContext.supportFragmentManager, 5)

    vp_home_detail.offscreenPageLimit = 5
    tl_home_detail_bar.setupWithViewPager(vp_home_detail)

}

}

HomeDetailPagerAdapter.kt

class HomeDetailPagerAdapter (fm : FragmentManager, val fragmentCount : Int): FragmentStatePagerAdapter(fm){

private val fragmentTitleList = mutableListOf("전체", "요가","발레", "태권도", "헬스")

override fun getItem(position:Int): Fragment{

    when(position){
        0-> return HomeFragment()
        1-> return WholeFragment()
        2-> return YogaFragment()
        3-> return BalletFragment()
        4-> return TakFragment()
        else -> return HomeFragment()
    }
}

override fun getPageTitle(position: Int):CharSequence?{
    return fragmentTitleList[position]
}
override fun getCount(): Int = fragmentCount

}

fragment_home_detail.xml

<RelativeLayout 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"
android:background="#f2f7ff"
tools:context=".ui.home.HomeDetailFragment">

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tl_home_detail_bar"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="#ffffff"
    app:tabIndicatorColor="#2c77f1"
    android:layout_alignParentTop="true"
    android:theme="@style/HomeDetailTab"
    android:elevation="5dp" />

<androidx.viewpager.widget.ViewPager
    android:id="@+id/vp_home_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/tl_home_detail_bar"/>

1 个答案:

答案 0 :(得分:0)

使用childFragmentManager代替myContext.supportFragmentManager

vp_home_detail.adapter = HomeDetailPagerAdapter(childFragmentManager, 5)