简体   繁体   中英

Error while explicitly casting Android's RecyclerView's ViewHolder in Kotlin: 'This cast can never succeed'

In Android, I am working on a library to make implementation of RecyclerView easy. I also want that once a developer has added this library as a dependency in app build.gradle , adding RecyclerView dependency in app build.gradle shouldn't be required. This library will basically be like a wrapper on RecyclerView .

I handled the view part by inflating RecyclerView dynamically in the library. For LayoutManager , I created a class based on Factory Design Pattern, where the developer can choose which LayoutManager and configuration he wants. But I faced an issue when implementing Adapter and ViewHolder wrapper classes.

Attempt #1

open class ViewHolder(view: View) : RecyclerView.ViewHolder(view)

Error: Missing super type dependency (which meant RecyclerView dependency needs to be present in app build.gradle )

Attempt #2

class ViewHolder(view: View)

and wherever I was using it internally in the library, I tried casing it explicitly as viewHolder as ViewHolder or adapter as RecyclerView.Adapter

Error: This cast can never succeed.

Please guide me regarding this, how can I achieve a 100% wrapper on RecyclerView ?

Your library presumably depends on the RecyclerView library with the following line:

implementation "com.android.support:recyclerview-v7:$version"

By using implementation you are not exposing this dependency to modules that depend on your library. Therefore, users of your ViewHolder class will not know about the RecyclerView.ViewHolder class and it causes the described error.

Try using api to propagate this dependency up the module chain:

api "com.android.support:recyclerview-v7:$version"

Read about the differences here or here .


Update : You can create a wrapper class and hide the property using internal visibility:

open class ViewHolder(view: View) {
    internal val recyclerHolder = RecyclerView.ViewHolder(view)
}

This is similar to solution #2 but instead of casting to RecyclerView.ViewHolder, you use the property.

Try this way into make viewholder class.

class ItemViewHolder : RecyclerView.ViewHolder {
 constructor(itemView: View) : super(itemView){}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM