首页 > 解决方案 > RecyclerView 适配器无法工作

问题描述

问题很简单,我使用了 recyclerview 适配器并设置在 mainactivity.A 应用程序启动但适配器字段只是白色空白。没有错误。当我调试时,我看到 Adapter 构造方法工作但 onBindViewHolder 没有工作。

MainActivity OnCreate 方法

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    productList = new ArrayList<>();
    productAdapter = new ProductAdapter(this,productList);


    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

   productList = dbHelper.getAllProducts();
   productAdapter.notifyDataSetChanged();     
   ...
}

标签: androidandroid-recyclerview

解决方案


您将适配器的内容设置为产品列表,然后将该变量替换为dbHelper.getAllProducts()

解决方案 1:使用productList.addAll(dbHelper.getAllProducts())

解决方案2:将内容的setter添加到适配器并在最后使用adapter.setData(dbHelper.getAllProducts())或添加adapter.setData(productList)


推荐阅读