I need a help.
requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.nav_host_fragment, testFragment) .addToBackStack(testFragment.tag) .commit()
TestFragment.kt →worked
TestAdapter.kt →didn't work →requireActivity() seems to be unavailable.
What is the difference? And what should I do to display TestFragment in TestAdapter.kt? There is a button for click in TestAdapter.kt. That's why I need to do this.
CodePudding user response:
An Adapter is not a Fragment, so it doesn't have the same functions available that Fragment does. If you need an Activity reference inside an Adapter (which you shouldn't because that is poor design--poor encapsulation), you need to add a constructor parameter or property to your class that allows you to pass an Activity reference to your Adapter. For example:
class ExpandableListAdapter(val activity: Activity): ListAdapter { //...
and then when you create it in your Fragment, you could pass requireActivity()
as a constructor parameter.
But like I said, this would be poor encapsulation. Maybe you just need a Context
reference for when you're creating view holders? In that case, you can get it from the parent
parameter:
override fun createViewHolder(parent: ViewGroup, viewType: Int) {
val context = parent.context
// use context to create view holder's layout
}