Group Group Group Group Group Group Group Group Group

ViewPager2 in Android: Getting Started | raywenderlich.com

In this tutorial for Android, you’ll learn to use the new ViewPager2 widget. Along the way you will build an app to show celebrity doppelganger animals.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/8192680-viewpager2-in-android-getting-started

In article, after completing TODO3 & running app; my questions:

  1. How does layout of widget.ViewPager2 (main_activity.xml) get inflated or get activated? (once we removed the add Fragment from MainActivity).
  2. You explained under the hood about FragmentStateHandler but were vague about it’s relationship to ViewPager2 (I’m thinking back to the widget declaration in #1 above). How/where do those two get associated?
  3. In DoppelgangerFragment.kt, re: the companion object. It seems unnecessary, that it would be clearer for the properties to be associated with the fragment instance, say in an init {}.
    class DoppelgangerFragment: Fragment (val position: Int) {
    init {
    val bundle = Bundle()
    bundle.putInt( ARG_POSITION, position)
    this.arguments = bundle
    }
    }
    (I’m from the Ruby world, forgive my naivety!)
  4. why is the bundle.putInt / arguments even necessary if you have that information in an instance property? won’t that always be there when the fragment is invoked?

One final question re TabLayoutMediator. You say “if you look at the constructor of TabLayoutMediator, you’ll understand what’s happening in the code.” Umm, actually I don’t. Specifically, for the third parameter [TabConfigurationStrategy tabConfigurationStrategy] which is an interface, I don’t see how you can tell that you are able to pass a lambda (question 1), and that the lambda doesn’t have to deal with fun onConfigureTab(tab: TabLayout.Tab, position: Int) in the lambda (question 2).
The lambda given was:
{ tab, position -> tab.text = doppelgangerNamesArray[position].split(" ")[0] }

@rajdeep1008 Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hello, to follow up on your presentation, is it possible to have a tablayout with a tab 1 which displays a fragment and a tab 2 which displays another fragment. thank you

I migrated to ViewPager2, and made my views Fragments. Now the performance when swiping from left to right is bad. It takes longer and it’s not smooth anymore.

I’ve opened up a SO thread. For now I’m gonna migrate back to the good performing old code.