Create a RecyclerView with multiple view from layouts

前端 未结 3 874
傲寒
傲寒 2020-12-06 16:14

I am trying to have 2 layout in one RecyclerView

I have a recycler view list which is called Bookmark and it is parsed from an xml and this is all working , but I wa

3条回答
  •  既然无缘
    2020-12-06 16:39

    Do this operations in your Activity.

            ArrayList  data = new ArrayList<>();
            //data.addAll(your array list bookmark); uncomment this line add your all array list of bookmark
            Bookmark d = new Bookmark(0);
            data.add(d);
            mList.setAdapter(new BookMarkAdapter(activity, data));
    

    Try This adapter

    public class BookMarkAdapter extends RecyclerView.Adapter {
    
    private Context context;
    private ArrayList data;
    
    public BookMarkAdapter(Context context, ArrayList data) {
        this.context = context;
        this.data = data;
    }
    
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == 1)
            return new ViewBookmarkHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_with_normal_image_and_textview, parent, false));
        else
            return new AddBookmarkHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_with_image, parent, false));
    
    }
    
    
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    
        Bookmark d = data.get(position);
    
         if (d.getType()==1) {
            ViewBookmarkHolder viewBookmarkHolder =(ViewBookmarkHolder) holder;
            // do your show image and textview operation here
        } else {
    
            AddBookmarkHolder addBookmarkHolder =(AddBookmarkHolder) holder;
            // do your on click operation here. Like adding new bookmark and update your arraylist and notify data changed for adapter.
        }
    }
    
    @Override
    public int getItemViewType(int position) {
        return data.get(position).getType();
    }
    
    @Override
    public int getItemCount() {
        return data.size();
     }
    }
    

    Update this methods and variables in your Bookmark Pojo

    public class Bookmark {
    
        private Integer type;
    
        public Bookmark(Integer type) {
            this.type = type;
        }
    
        public void setType(Integer type) {
            this.type = type;
        }
    
        public Integer getType() {
            if(type==null)
                return 1;
            return type;
        }
      }
    

提交回复
热议问题