0

Inside RecyclerView.Adapter, can we change the main view that we put in viewholder from onCreateViewHolder method like

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.inflate_common_item, viewGroup, false);
        ViewHolder vh = new ViewHolder(mView);
        return vh;
    } 
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
    if(viewHolder instanceof ViewHolder) {
        View view = new View(mContext);
         view.setBackGroundColor(color);
        ViewHolder mViewHolder = (ViewHolder)viewHolder;
        mViewHolder.mMainView = view;
    } 
  }
 public static class ViewHolder extends RecyclerView.ViewHolder {
    protected View insideview;

    public ViewHolderFooter(View v) {

        super(v);
        insideview = v;

    }

}

But it's not changing the main view and not even throwing any exception. Please help me understand the point why it is so? Is it that viewholder save our view to reuse if we again scroll through that view or something else?

Ankur Chaudhary
  • 2,709
  • 3
  • 19
  • 30

1 Answers1

2

Answering your question:

Is it that viewholder save our view to reuse if we again scroll through that view or something else?

Yes, the ViewHolder is used to "cache" the view type so you can reuse and speed up all the view-instance-creating inside the RecyclerView.

Although there a little mistake in your code (ViewHolderFooter in a ViewHolder named class) I could suggest you to read the answer in these well answered question - that I think will be usefull to you.

How to create RecyclerView with multiple view type?

Basically, you need to implement the getItemViewType() method to let you use more than one ViewHolder inside the RecyclerView.

Community
  • 1
  • 1
krumikaze
  • 67
  • 3
  • 8
  • my main question is can we change main view in onBinderViewHolder() – Ankur Chaudhary Jun 04 '15 at 04:53
  • You can't change it in `onBindViewHolder()`. You have to use the `getItemViewType` in combination with the onBindViewHolder to achieve what you want (you have to know the number of viewholder types). If that behavior doesn't fit to your needs, please try to explain the use-case, so I can provide a better support – krumikaze Jun 05 '15 at 10:13