13

I would like to create my own version of custom ViewPager2 view from extending from the original Viewpager2, but just had a hard time doing it. I get errors such as

Cannot inherit from final 'androidx.viewpager2.widget.ViewPager2'

Is there a better way to extend from a Viewpager2 so that I could add cusotm functionality?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

4 Answers4

26

If you want to extend it just because you need Not-Swipeable behaviour, you dont need to do it. ViewPager2 provides nice property called : isUserInputEnabled

momvart
  • 1,737
  • 1
  • 20
  • 32
Andrej Sitár
  • 261
  • 3
  • 4
6

you can not extends ViewPager2, because it's final class as mentioned in link

https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2

1

Create a class called "MyViewPager2". Add ViewPager2 as a variable in the new class. Now you can override all of the ViewPage2 methods in the new class and of course, you are able to extend from "MyViewPager2".

Majid Sadeghi
  • 180
  • 11
0

It's clear from the message that it's a final call so you can't inherit from it. However if you care using Kotlin you can use extensions to get some composition going but I am not sure what you want to do here.

NIKHIL MAURYA
  • 289
  • 1
  • 15
  • I have updated the question. Simply I would like to extend from it and add my own functionality to it. And would like to use java for it –  Dec 04 '19 at 09:19
  • What additional functionality you want? Do you have something specific thing in mind that can't be be done with a wrapper Class, which will, under the hood call the Viewpager class – NIKHIL MAURYA Dec 04 '19 at 09:27
  • Wrapper class?. This is something new to me. Please show how this could be done since it could be the answer I was looking for. And about the functionality, its no that much more important, i could figure out something else. Just wanted to a create a custom view from a ViewPager2 and still use all of its functionality –  Dec 04 '19 at 09:33
  • Wrapper class is not some software design concept that you need to know. It's just another class under which you can keep the ViewPager object so that you can hide all the complexities of the viewpager from the activity/fragment where you would be using it. The disadvantage compared to inheritance would be you won't have opportunity to override method and access protected fields. – NIKHIL MAURYA Dec 04 '19 at 09:40