How to set the adapter for an inner RecyclerView item without skipping the layout?

你离开我真会死。 提交于 2019-12-11 04:27:20

问题


I'm using a RecyclerView to display some data. For each item in my RecyclerView I have created a custom layout which holds beside other views a RecyclerView. So I have a nested RecyclerView under each item.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="180dp"
        android:layout_height="45dp"
        android:id="@+id/recycler_view"/>

    //Other text views
</RelativeLayout>

The layout for the inner RecyclerView is very simple, an ImageView for each item, like in the screenshot below:

This is my adapter class for the outer ReyclerView:

class UserViewHolder extends RecyclerView.ViewHolder {
    View itemView;
    RecyclerView recyclerView;

    UserViewHolder(View itemView) {
        super(itemView);
        this.itemView = itemView;
        recyclerView = itemView.findViewById(R.id.recycler_view);
    }

    void bind(User user) {
        itemView.setOnClickListener(view -> {
            //Move to user Activity
        });

        UserAdapter adapter = new UserAdapter(user.list);
        recyclerView.setAdapter(adapter);
    }
}

As you can see, I'm creating a new UserAdapter object for each RecyclerView that exist within my item so each inner RecyclerView to have its own adapter. Unfortunately I get:

No adapter attached; skipping layout

How to set the adapter for the inner RecyclerView, so I cannot get this error anymore? Can it be set outside my outer adapter class? Thanks!

Edit:

@Override
protected void onBindViewHolder(@NonNull UserViewHolder userViewHolder, int position, @NonNull User user) {
    userViewHolder.bind(user);
}

回答1:


What about doing like this:

class UserViewHolder extends RecyclerView.ViewHolder {

   View itemView;
   RecyclerView recyclerView;
   UserAdapter adapter;

   UserViewHolder(View itemView) {
       super(itemView);
       this.itemView = itemView;
       recyclerView = itemView.findViewById(R.id.recycler_view);
       adapter = new UserAdapter(user.list);

       itemView.setOnClickListener(view -> {
        //Move to user Activity
       });
       recyclerView.setAdapter(adapter);

   }

   void bind(User user) {

       adapter.setUser(user);            // update you adapter dataset here
       adatper.notifyDataSetChanged();

   }
}

So, void bind is used only to update the adapter dataset...



来源:https://stackoverflow.com/questions/55515177/how-to-set-the-adapter-for-an-inner-recyclerview-item-without-skipping-the-layou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!