Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change layout for all items in RecyclerView?

I have a RecyclerView. In adapter I have a boolean flag to determine which of layout should be used for all items:

public class MyAdapter extends RecyclerView.Adapter<MyHolder> {

    private boolean mIsSecondModeEnabled;

    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(mIsSecondModeEnabled ?
         R.layout.layout_second_mode_item :
         R.layout.layout_first_mode_item, parent, false);
        return new MyHolder(view);
    }

    public void setModeEnabled(boolean enabled) {
        mIsSecondModeEnabled = enabled;
        notifyDataSetChanged();
    }
}

This code doesn't work completely right. When I call setModeEnabled(true) some items showing with layout_first_mode_item layout.

How to achieve it?

like image 809
BArtWell Avatar asked Mar 01 '17 14:03

BArtWell


1 Answers

onCreateViewHolder() will be called, when there are no ViewHolders in the pool of already created ViewHolders. In this callback you specify what view you want RecyclerView to create for you.

onCreateViewHolder() will not necessarily be called after you have performed notifyDataSetChanged(). Instead onBindViewHolder() will be triggered. This is the place where you should update your view.

Override getItemViewType() and return the layout id depending on your use case:

@Override
public int getItemViewType(final int position) {
    return mIsSecondModeEnabled ? R.layout.my_layout_1 : R.layout.my_layout_2;
}

Create 2 ViewHolder classes for those two layouts and from onCreateViewHolder() return appropriate ViewHolder depending on the viewType parameter of onCreateViewHolder() callback.

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == R.layout.my_layout_1) {
        // create FirstViewHolder
    } else if (viewType == R.layout.my_layout_2) {
        // create SecondViewHolder
    }
    // return created ViewHolder
}

Then in onBindViewHolder() callback setup your views.

like image 62
azizbekian Avatar answered Sep 29 '22 14:09

azizbekian