我正在尝试在我的应用程序上使用MVVM
来获取一些数据,并使用Retrofit
将其显示在RecyclerView
上,但是未显示任何内容,正在记录数据,当我直接从我的 Activity 中调用改造实例时,正在显示数据在我的RecyclerView
上,不确定做错了什么。
这是我的适配器的外观
class CategoryAdapter (val context: Context):RecyclerView.Adapter<CategoryAdapter.CategoryView>(){
var category : List<Category> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryAdapter.CategoryView {
val view = LayoutInflater.from(parent.context).inflate(R.layout.category_item, parent, false)
return CategoryView(view)
}
override fun getItemCount(): Int {
return category.size
}
override fun onBindViewHolder(holder:CategoryView, position: Int) {
val category = category[position]
holder.categoryName.text = category.name
}
class CategoryView(itemView: View, var category: Category? = null) : RecyclerView.ViewHolder(itemView){
val categoryName: TextView = itemView.findViewById(R.id.category_title)
}
}
我的
ViewModel
fun loadCategories(id:Int): MutableLiveData<List<Category>>? {
var categoryList: MutableLiveData<List<Category>>? = null
RetrofitClient.makeRetrofitApi2().getCategoryProducts(id)
.enqueue(object : Callback<List<Category>> {
override fun onResponse(call: Call<List<Category>>, response: Response<List<Category>>) {
categoryList?.value = response.body()
}
override fun onFailure(call: Call<List<Category>>, t: Throwable) {
}
})
return categoryList
}
我在 Activity 中如何称呼它
private fun productRecyclerView(){
recyclerView = findViewById(R.id.foodRv)
categoryAdapter = CategoryAdapter(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = categoryAdapter
userViewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
userViewModel!!.loadCategories(intent.getIntExtra("VENDOR_ID", 0))?.observe(this, Observer { categories ->
categoryAdapter = CategoryAdapter(this)
categoryAdapter!!.setCategories(categories)
foodRv!!.adapter = categoryAdapter
})
}
一切都已初始化。
最佳答案
您再次在Adapter
内初始化了Observer
并将其设置为foodRv
。那是故意的吗?
如果您需要recyclerView
来显示类别,则可以执行以下操作:
categoryAdapter!!.setCategories(categories)
categoryAdapter!!.notifyDataSetChanged()
关于android - 使用MVVM和翻新不会获取任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016550/