M
M
MikkiMouse2015-10-26 14:11:35
Android
MikkiMouse, 2015-10-26 14:11:35

How to change ViewHolder on the go?

Good afternoon, such a problem:
There is a filled RecyclerView
In the adapter for this RecyclerView, I made two types of ViewHolders: VHItem_1 and VHItem_2
By default, VHItem_1 is shown.
I want all VHItem_1 to change to VHItem_2 when the button is pressed in the application.
How can this be done?

private static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  ...
  
  public RecyclerViewAdapter(Context context, ArrayList<MyObject> dataset) {
    mDataset= dataset;
    mCondition = true;
  }

  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v;
    if(mCondition) {
      v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_1, parent, false);
      return new VHItem_1(v);
    } else {
      v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_2, parent, false);
      return new VHItem_2(v);
    }
  }
  
  @Override
  public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    if(mCondition) {
      VHItem_1 itemHolder = (VHItem_1) holder;
      itemHolder.setItem(position);
    } else {
      VHItem_2 itemHolder = (VHItem_2) holder;
      itemHolder.setItem(position);
    }
  }

  @Override
  public int getItemCount() {
    return mDataSet.size();
  }

  @Override
  public int getItemViewType(int position) {
    if(mCondition)
      return 0;
    else
      return 1;
  }
  
  public void changeCondition(boolean value) {
    mCondition = value;
    notifyDataSetChanged();
  }
  
  
  
  class VHItem_1 extends RecyclerView.ViewHolder {
    ...
  }
  
  class VHItem_2 extends RecyclerView.ViewHolder {
    ...
  }
}

It turns out after clicking on the button I call the changeCondition() method and get an error about the impossibility of converting VHItem_1 to VHItem_2. How to be?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question