【发布时间】:2020-08-15 12:09:20
【问题描述】:
我正在尝试在我的适配器类中使用泛型。这是我尝试过的:
class ItemAdapter<I>(
options: FirestoreRecyclerOptions<I>
): FirestoreRecyclerAdapter<I, ItemAdapter<I>.ItemViewHolder<I>>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder<I> {
val layoutInflater = LayoutInflater.from(parent.context)
val dataBinding = inflate(layoutInflater, parent, false)
return ItemViewHolder(dataBinding)
}
override fun onBindViewHolder(holder: ItemViewHolder<I>, position: Int, item: I) {
holder.bindItem(item)
}
inner class ItemViewHolder<I>(
private val dataBinding: ItemDataBinding
) : RecyclerView.ViewHolder(dataBinding.root) {
fun bindItem(item: I) {
dataBinding.item = item //Here is the problem
}
}
}
这是我的布局文件:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data class="ItemDataBinding">
<variable
name="item"
type="com.example.myapp.Item" />
</data>
<TextView
android:id="@+id/item_name_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{item.name}" />
</layout>
我添加了 item 对象,因此我可以访问 name 字段。然而,Android Studio 在这行抱怨:
dataBinding.item = item
与:
Type mismatch.
Required: Item!
Found: I
如何正确使用泛型并摆脱这个问题?谢谢
编辑:
我不需要将特定的类设为通用。我需要以某种方式将该item 对象转换为特定类的对象。我试图在名为classType: Class<I> 的类中添加一个新属性并使用:
dataBinding.item = item as classType
但没有任何运气。我也试过:
dataBinding.item = item as I
再次没有运气。
【问题讨论】:
-
这能回答你的问题吗? Data binding generic variable
-
@ADM 不,因为我不想让
Item类通用,我需要以某种方式使布局文件中的项目对象以某种方式通用。该项目可以成为Product对象、User对象等等。 -
那么你的变量类型应该是 item 的父类型而不是 item ..
-
@ADM 我不明白你在上一条评论中所说的内容。
-
@ADM 我已经编辑了我的问题。
标签: android kotlin generics google-cloud-firestore android-databinding