简体   繁体   English

Android RecyclerView.Adapter的泛型

[英]Generics for RecyclerView.Adapter Android

I am trying to use a common extension function for all RecyclerView.Adapter in my app so I created an ext fun called notifyAdapter, But it is not working as expected. 我正在尝试对我的应用程序中的所有RecyclerView.Adapter使用通用扩展功能,因此我创建了一个名为notifyAdapter的ext娱乐程序,但是它没有按预期工作。

fun <T> RecyclerView.Adapter<RecyclerView.ViewHolder>.notifyAdapter() {
    updateAll()
    notifyDataSetChanged()
}

When i use 当我使用

offlineListAdapter.notifyAdapter() or onlineListAdapter.notifyAdapter() offlineListAdapter.notifyAdapter()onlineListAdapter.notifyAdapter()

it throws 它抛出

Cannot be applied to receiver OfflineListAdapter 无法应用于接收器OfflineListAdapter

OfflineListAdapter.kt OfflineListAdapter.kt

    class OfflineListAdapter : RecyclerView.Adapter<OfflineListAdapter.OfflineListHolder>() {

      class OfflineListHolder(view: View) : RecyclerView.ViewHolder(view) {

      }
    }

How can I create a common extension function for all RecyclerView.Adapter using Generics. 如何使用泛型为所有RecyclerView.Adapter创建通用扩展功能。

Thanks in advance. 提前致谢。

There are a couple ways to do this. 有两种方法可以做到这一点。

  1. You can mark the ViewHolder parameter with out variance. 您可以标记ViewHolder与参数out变化。 This way your function isn't generic, so you won't have access to the exact type of the ViewHolder in it. 这样,您的函数就不是通用的,因此您将无法访问其中的ViewHolder的确切类型。

     fun RecyclerView.Adapter<out RecyclerView.ViewHolder>.notifyAdapter() { ... } 
  2. Alternatively, you can have a generic type parameter for the function that's bound to be a subclass of ViewHolder . 另外,您可以为该函数提供一个泛型类型参数,该参数必须是ViewHolder的子类。 This way you can use T inside the function, for example, you could create a listOf<T>() if you wanted to. 这样,您可以在函数内部使用T ,例如,如果需要,可以创建listOf<T>()

     fun <T : RecyclerView.ViewHolder> RecyclerView.Adapter<T>.notifyAdapter() { ... } 
  3. Finally, you could also use star projection, which I believe in this case will give you the exact same result as the first solution, since the type argument of the Adapter class has an upper bound of ViewHolder . 最后,您还可以使用星形投影,我相信在这种情况下,它会为您提供与第一个解决方案完全相同的结果,因为Adapter类的type参数具有ViewHolder的上限。

     fun RecyclerView.Adapter<*>.notifyAdapter() { ... } 

You can read in more detail about variance and projections in the offical documentation here . 您可以在此处的官方文档中详细了解方差和预测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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