Home > OS >  I can't define supportFragmentManager with kotlin in fragment
I can't define supportFragmentManager with kotlin in fragment

Time:02-26

class DataFragment : Fragment() {

private var _binding: FragmentDataBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val adapter = MyViewPagerAdapter(supportFragmentManager)

    adapter.addFragment(DataFragment(), "Günlük")
    adapter.addFragment(Data2Fragment(), "Aylık")
    adapter.addFragment(Data3Fragment(), "Yıllık")

    viewPager.adapter = adapter
    tabs.setupWithViewPager(viewPager)

}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentDataBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

I designed a tabLayout and placed it inside the fragment named DataFragment. I opened different fragments named daily, monthly, yearly and added this to the code. But I can't define supportFragmentManager here. It gives an Unresolved reference error.

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {

private val fragmentList: MutableList<Fragment> = ArrayList()
private val titleList: MutableList<String> = ArrayList()

override fun getItem(position: Int): Fragment {
    return fragmentList[position]
}
override fun getCount(): Int {
    return fragmentList.size
}
fun addFragment(fragment: Fragment, title: String) {
    fragmentList.add(fragment)
    titleList.add(title)
}
override fun getPageTitle(position: Int): CharSequence? {
    return titleList[position]
}

Here are the codes of the adapter I defined.

CodePudding user response:

requireActivity().supportFragmentManager

CodePudding user response:

You must call it from the parent activity, not directly from the fragment

Simple like the code below:

 activity?.supportFragmentManager?.beginTransaction()
  • Related