我从一个api中获得了一些类别,并试图在回收器视图上查看它们,但它不起作用:Main Activity:`@AndroidEntryPointclass MainActivity:AppCompatActivity(){private val TAG=“MEALZ”private lateinit var binding:ActivityMainBindingprivate val viewModel:MeaslViewModel by viewModels()override fun onCreate(savedInstanceState:Bundle?){super.onCreate(savedInstance State)binding=ActivityMainBinding.fluge(layoutInflationer)setContentView(binding.root)
val adapter = CategoryAdapter(this) binding.categoriesRv.adapter = adapter viewModel.getMeals() lifecycleScope.launch { viewModel.categories.collect { adapter.setData(it?.categories as List<Category>) Log.d(TAG, "onCreate: ${it?.categories}") } } }
}`类别适配器:
`class CategoryAdapter(private val context:context?):RecyclerView.Adapter<;类别适配器类别视图持有者>;(){private var categoryList:MutableList<;Category?>;=mutableListOf<;类别?>;()
inner class CategoryViewHolder(itemView: CategoryLayoutBinding) : RecyclerView.ViewHolder(itemView.root) { val name = itemView.categoryNameTv val img = itemView.categoryIv val des = itemView.categoryDesTv } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder { val binding = CategoryLayoutBinding.inflate(LayoutInflater.from(context), parent, false) return CategoryViewHolder(binding) } override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) { var category = categoryList[position] holder.name.text = category?.strCategory holder.des.text = category?.strCategoryDescription Glide.with(context as Context).load(category?.strCategoryThumb).into(holder.img) } override fun getItemCount(): Int { return categoryList.size } fun setData(CategoryList: List<Category>) { this.categoryList.addAll(CategoryList) notifyDataSetChanged() //to notify adapter that new data change has been happened to adapt it }
}`