0

I have been using the following adapter class for ViewPager. It was converted to Kotlin from java.

class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
    private val mFragmentList = ArrayList<Fragment>()
    private val mFragmentTitleList = ArrayList<String>()

    override fun getItem(position: Int): Fragment {
        return mFragmentList[position]
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList[position]
    }
}

To minimize number of lines I tried using Kotlin Pair. And convert the above implementation to the following. Now I am curious about the performance of this implementation using Pair. Could I get a logical explanation on this?

class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
    private val pairs = ArrayList<Pair<Fragment, String>>()
    fun addFragment(fragment: Fragment, title: String) = pairs.add(Pair(fragment, title))
    override fun getItem(position: Int): Fragment = pairs[position].first
    override fun getCount(): Int = pairs.size
    override fun getPageTitle(position: Int): CharSequence? = pairs[position].second
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sagar Chapagain
  • 1,683
  • 2
  • 16
  • 26
  • 2
    Are you sure it is a good idea to store fragments when using adapter? Maybe you should have a look at this: https://stackoverflow.com/questions/7951730/viewpager-and-fragments-whats-the-right-way-to-store-fragments-state – Leandro Ocampo Jan 02 '18 at 16:42
  • We need to define which fragments should be shown in viewpager, above implementation extending `FragmentPagerAdapter` will facilitate this and do other internal hard works itself. I think this is widely accepted implementation and is used by most people. – Sagar Chapagain Jan 03 '18 at 09:33

1 Answers1

1

Using a Pair clearly improves readability and maintainability, so go with that.

But I would even go further an use a Map instead, if there wasn't the constraint that you need to access the elements via index (getItem(position: Int)).

private val fragmentToTitleMap = HashMap<Fragment, String>()

Add to it:

fragmentToTitleMap[someFragment] = "someTitle"

Don't think too much about micro-optimization. It should not make a noticeable difference in this case, since you won't have +100 Fragments.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • Since we have to use position(int value) which is used in override functions, so I am sticking with the list of Pair and follow your thought on micro-optimization :) – Sagar Chapagain Jan 03 '18 at 09:47