gpt4 book ai didi

android-recyclerview - 如何将该Firebase Recycler Adapter实现转换为Adapter.kt类?

转载 作者:行者123 更新时间:2023-12-02 13:38:33 26 4
gpt4 key购买 nike

我已经编写了Kotlin FirebaseRecyclerAdapter,它可以作为MainActivity的一部分正常工作。但是,我想将此代码放在单独的MainAdapter.kt文件/类中。我怎样才能做到这一点?

var query = FirebaseDatabase.getInstance()
.reference
.child("").child("categories")
.limitToLast(50)

val options = FirebaseRecyclerOptions.Builder<Category>()
.setQuery(query, Category::class.java)
.setLifecycleOwner(this)
.build()

val adapter = object : FirebaseRecyclerAdapter<Category, CategoryHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryHolder {
return CategoryHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.category_row, parent, false))
}

protected override fun onBindViewHolder(holder: CategoryHolder, position: Int, model: Category) {
holder.bind(model)
}

override fun onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
}
}

class CategoryHolder(val customView: View, var category: Category? = null) : RecyclerView.ViewHolder(customView) {

fun bind(category: Category) {
with(category) {
customView.textView_name?.text = category.name
customView.textView_description?.text = category.description
}
}
}

最佳答案

根据您的代码,您可以执行以下操作:

class MainAdapter(lifecycleOwner: LifecycleOwner) : FirebaseRecyclerAdapter<Category, CategoryHolder>(buildOptions(lifecycleOwner)) {

companion object {
private fun buildQuery() = FirebaseDatabase.getInstance()
.reference
.child("").child("categories")
.limitToLast(50)

private fun buildOptions(lifecycleOwner:LifecycleOwner) = FirebaseRecyclerOptions.Builder<Category>()
.setQuery(buildQuery(), Category::class.java)
.setLifecycleOwner(lifecycleOwner)
.build()

}

class CategoryHolder(val customView: View, var category: Category? = null) : RecyclerView.ViewHolder(customView) {

fun bind(category: Category) {
with(category) {
customView.textView_name?.text = category.name
customView.textView_description?.text = category.description
}
}
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryHolder {
return CategoryHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.category_row, parent, false))
}

protected override fun onBindViewHolder(holder: CategoryHolder, position: Int, model: Category) {
holder.bind(model)
}

override fun onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
}
}

还有许多其他方法可以解决此问题,这只是您的封装版本。

关于android-recyclerview - 如何将该Firebase Recycler Adapter实现转换为Adapter.kt类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com