Search code examples
androidkotlinandroid-pageradapterkotlin-android-extensions

How to solve issue with PagerAdapter on Kotlin: "Required method instantiateItem was not overridden"?


So my project is calling Kotlin file to Java :

This is the error message (Run Time Error) I got:
java.lang.UnsupportedOperationException: Required method instantiateItem was not overridden



this is my app gradle

apply plugin: 'kotlin-android'
android {
    compileSdkVersion 26
....
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
....
    implementation "org.jetbrains.kotlin:kotlin-stdlib"
}

my project gradle looks:

buildscript {
    ext.kotlin_version = '1.2.61'
    repositories {
...

}
dependencies {
....
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}






and last, this is my kotlin code,

class SwipeAdapter : PagerAdapter {
....
...
    override fun instantiateItem(container: ViewGroup?, position: Int):Any {
      .....
     ....
        return super.instantiateItem(container, position)
    }

    .....
}

(I tried to change it to java.lang.Object but of course got a compilation error, it must be type of Any for Kotlin)

called on java file:

PagerAdapter sa= new SwipeAdapter(someArgs);

Solution

  • You're getting the exception because you're still delegating the work to the super call, which then calls into this implementation:

    @Deprecated
    @NonNull
    public Object instantiateItem(@NonNull View container, int position) {
        throw new UnsupportedOperationException(
                "Required method instantiateItem was not overridden");
    }
    

    Instead of calling the super method, you should return an object you create that represents the page at the given position. This is usually the View itself, see this question or this tutorial for PagerAdapter examples.