Skip to content Skip to sidebar Skip to footer

How To Change The Viewtype Of A Recyclerview Item Onclick

I have created a RecyclerView with Cards as its primary viewtype. What I am trying to achieve is that when user clicks on a item the ViewType of that item is changed from cards to

Solution 1:

see my example:

// RecycleItemObject.javapublicclassRecycleItemObject {
       publicstaticint LAYOUT_ITEM_PORTRAIN = 0;
       publicstaticint LAYOUT_ITEM_LANDSCAPE = 1;
       privateint type;
         ....................
      /**
      * @return get layout type of item
      */publicintgetType() {
        return type;
      }

      /**
      * set layout type of item
      * @param type
      */publicvoidsetType(int type) {
         this.type = type;
      }
  }

 // adapterpublic Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;
    if (viewType == RecycleItemObject.LAYOUT_ITEM_PORTRAIN) {
        view = LayoutInflater.from(context).inflate(R.layout.item_recycle_view_main, parent, false);
    } else {
        view = LayoutInflater.from(context).inflate(R.layout.item_recycle_view_main_land, parent, false);
    }
 }

// event click item
@onClick....
curentObject.setType(RecycleItemObject.LAYOUT_ITEM_LANDSCAPE);
// notify item only
notifyItemChanged(itemPosition);

with me it work fine

Solution 2:

Hope you have figured out your problem. If not then,I have done it f or you. The buggy line is

@OverridepublicvoidonClick(View v) {
        itemClickedState.add(getAdapterPosition(), clickedState.SHOW_SECONDARY_CONTENT);
    } 

Here what you are doing is adding a new Item to

 itemClickedState.add(getAdapterPosition(), clickedState.SHOW_SECONDARY_CONTENT);

This will insert a new item and size of mdataList and itemClickState differs and hence mis matching happens.

Use itemClickedState.set(getAdapterPosition(), clickedState.SHOW_SECONDARY_CONTENT); instead. And second thing I does not understand what tvTicketClass is . If it is a single TextView, then you should concatenate the string first and them do tvTicketClass.settext(concatenatedstrClass) . Hope you get helped from this post.If have any further issue , please do comment.

Solution 3:

override getItemViewType in adapter and return itemtype you want. for more check out this link https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView

Post a Comment for "How To Change The Viewtype Of A Recyclerview Item Onclick"