Mihai Potra
04/14/2023, 4:26 PMclass MyFragmentAdapter: FragmentStateAdapter
subclass to use with a ViewPager2 list of fragments. Inside it I store an array of MyFragment: Fragment
classes (i.e. MyFirstFragment: MyFragment
and MySecondFragment: MyFragment
) that I then instantiate inside FragmentStateAdapter.createFragment(position: Int)
by invoking something like myClassesList[position].newInstance()
. It is my understanding that instantiating MyFragment
subclasses inside this function is better, because it manages memory allocation and deallocation (instantiate and destroy) automatically. But this means that I need to create MyFragment
subclasses for each different Fragment even if code is the same, only layout differs.
My question is: Do object expression such as object: MyFragment { }
also instantiate the Fragment? As far as I could read, these are only data classes, and do not allocate UI/state resources just from the Fragment
constructor - onCreate()
isn't invoked correct? And if I were to store in myClassesList
the object: MyFragment(layout_id: R.layout.some_layout_id)
could I still be able to somehow instantiate the Fragment inside createFragment(position: Int)
? Do I still need to "deallocate" objects or does Kotlin automatically sort that out for me when MyFragmentAdapter.myClassesList
is destroyed?(MyFirstFrament::class.java).newInstance()
pretty much the same as object: MyFirstFragment {}
in terms of memory allocation (aside the anonymous object being a subclass of MyFirstFrament) ?MyFragmentAdapter
class, and instantiating MyFragment(layout_ids[position])
inside createFragment/1
so that no Fragment
instances are created outside the Adapter. If I'm wrong on this, please anyone let me knowIliya Gogolev
04/15/2023, 2:03 AM