recyclerview No adapter attached; skipping layout

后端 未结 30 3091
走了就别回头了
走了就别回头了 2020-11-21 04:51

Just implemented RecyclerView in my code, replacing ListView.

Everything works fine. The data is displayed.

But error messages are

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:24

    In your RecyclerView adapter class, for example MyRecyclerViewAdapter, make a constructor with the following params.

    MyRecyclerViewAdapter(Context context, List data) {
        this.mInflater = LayoutInflater.from(context); // <-- This is the line most people include me miss
        this.mData = data;
    }
    

    mData is the data that you'll pass to the adapter. It is optional if you have no data to be passed. mInflater is the LayoutInflater object that you have created and you use in the OnCreateViewHolder function of the adapter.

    After this, you attach the adapter in the MainActivity or wherever you want to on the main/UI thread properly like

    MyRecyclerViewAdapter recyclerAdapter;
    OurDataStuff mData;
    
        ....
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Like this:
    
            RecyclerView recyclerView = findViewById(R.id.recyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerAdapter = new RecyclerAdapter(this, mData); //this, is the context. mData is the data you want to pass if you have any
            recyclerView.setAdapter(recyclerAdapter);
        }
       ....
    

提交回复
热议问题