Given: RecyclerView with elements.

enter image description here

Necessary: To make it so that when adding new elements to the list, the last element that is there has not been changed and when you click on it, a new activation is opened

enter image description here

  @Override public void onBindViewHolder(CategoryViewHolder categoryViewHolder, int i) { if (i < getItemCount()-1) { // тут не делать ничего? } else { // последний элемент Category lastCategory = new Category("lasItem", R.drawable.ic_favorites); categories.add(lastCategory); } categoryViewHolder.bind(categories.get(i), listener); categoryViewHolder.categoryName.setText(categories.get(i).name); categoryViewHolder.categoryPhoto.setImageResource(categories.get(i).photoId); } 

    1 answer 1

    In order for RecyclerView to work, you make an adapter. The adapter creates items from some source, usually a list or cursor. Suppose the list is in the list field. You can add one immutable list item to the end as follows:

    First: the total number of elements will be the length of list + 1:

     @Override public int getItemCount() { if (list == null) return 0; return list.size() + 1; } 

    Second: when displaying the data for the last element, you show the pre-prepared element and plan a special action:

     @Override public void onBindViewHolder(OfferHolder holder, int position) { if (position < getItemCount()-1) { Offer o = list.get(position); holder.show(o, false); } else { // последний элемент holder.show(mySpecialOffer, true); } } 

    Third. In the holder, by the second parameter of the show() method, you define the behavior: either this is the standard action, or specific to the last element (in your case, the transition to a new activation).

    • please explain about onBindViewHolder I don’t quite understand, I added my own onBindViewHolder - java
    • onBindViewHolder is needed to show the necessary data in the created list item. The last element you have is special and lives its own life. This should be reflected in the code: for the last element there is a pre-prepared data, and there is a different behavior from the others. - tse
    • Please see the correct code change? - java
    • @java at a minimum, what you have outside the condition needs to be moved to where it says "do nothing." It seems that the answer is clearly visible - pavlofff
    • @pavlofff, already understood, thanks - java