Skip to content Skip to sidebar Skip to footer

How To Inflate Different Layout Using Same Recycle Adapter?

I am using wordAdapter class to recycle list view i want to inflate different layout on a give condition like if flag is equal to one than inflate activity_all layout and if flag i

Solution 1:

You can add this in onCreateViewHolder section

@NonNull@Overridepublic YouAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        if (viewType == 0)
        {
            Viewv= LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_one, parent, false);
            returnnewv;

        }else
        {
            Viewv= LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_two, parent, false);
            returnnewv;
        }

    }

Solution 2:

In your adapter class, you need to declare the type on the top like

privatestaticfinalint VIEW_ITEM = 1;
privatestaticfinalint LOADING = 0;
privatestaticfinalint VIEW_TYPE_EMPTY = 2;

And in the onCreateViewHolder you need to declare the ViewHolders like this

@Overridepublic RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                      int viewType) {

        RecyclerView.ViewHoldervh=null;

        switch (viewType) {

            case VIEW_TYPE_EMPTY:
                ViewemptyView= LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.item_view_no_data, parent, false);

                vh = newEmptyViewHolder(emptyView);
                break;

            case VIEW_ITEM:
                ViewitemView= LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.item_view_game_details, parent, false);

                vh = newGameViewHolder(itemView);
                break;

            case LOADING:
                Viewv= LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.layout_progress_bar, parent, false);

                vh = newProgressViewHolder(v);
                break;

        }

        return vh;
    }

And in onBindViewHolder you need to first check the instance of viewholder and the typecast according to the instance

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        if (holder instanceof GameViewHolder) {
           /** You code for you ViewHlder**/

        } else if (holder instanceof ProgressViewHolder) {
            /** You code for you ViewHlder
            ((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
            **/
        }
    }

Post a Comment for "How To Inflate Different Layout Using Same Recycle Adapter?"