https://kotlinlang.org logo
Title
m

Mihai Potra

04/14/2023, 4:26 PM
Hey folks! Newbie here. I'm using a
class 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?
On second thought: Is
(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) ?
I think I may have answered myself above 🤦 - I ended up just storing the layout ids in the
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 know
Also, it’s better to use a composable version of the view pager and avoid fragments 🙂