I am transforming my ListView to RecyclerView using Support Library v7.
I have 2 different layouts to load in a RecyclerView
. In ListView
, I was getting the position of the item in the getView()
method and able to load an appropriate layout for that row. But in RecyclerView
the onCreateViewHolder
doesn't have the position parameter.
Is there any other way to achieve this?
PS:The Inbox app from Google shows different layouts in a RecyclerView
(might be). I don't think they might have used the ListView
because of the performance improvements in RecyclerView
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v=null;
MyVO vo = voList.get(???POSITION???);
switch(vo.getType()){
case TYPE_1:
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout1, viewGroup, false);
break;
case TYPE_2:
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout2, viewGroup, false);
break;
}
return new ViewHolder(v);
}
Firstly, override getItemViewType
method:
@Override
public int getItemViewType(int position) {
//Implement your logic here
MyVO vo = voList.get(position);
return vo.getType();
}
Then you can simply use the second parameter of the onCreateViewHolder
:
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v=null;
switch(viewType){
case TYPE_1:
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout1, viewGroup, false);
break;
case TYPE_2:
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout2, viewGroup, false);
break;
}
return new ViewHolder(v);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With