I have a problem with sorting RecyclerView
items with different types. For example I have such RecyclerView.Adapter
:
public class StudyRVadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<Item> data;
public RVadapter(List<Item> src){
data = src;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
RecyclerView.ViewHolder vh;
switch (viewType){
case 0:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_0, parent, false);
vh = new ViewHolderZero(view);
break;
case 1:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_1, parent, false);
vh = new ViewHolderOne(view);
break;
default: vh=null;
}
return vh;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (Item0.class.isInstance(data.get(position))){
Item0 item0 = (Item0)data.get(position);
((ViewHolderZero)holder).text.setText(item0.toStringText());
}
if (Item1.class.isInstance(data.get(position))){
Item1 item1 = (Item1)data.get(position);
((ViewHolderOne)holder).text.setText(item1.toStringText());
}
}
@Override
public int getItemViewType(int position) throws IllegalArgumentException {
Item item = data.get(position);
if (Item0.class.isInstance(item)) return 0;
if (Item1.class.isInstance(item)) return 1;
throw new IllegalArgumentException("Unknown element");
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolderZero extends RecyclerView.ViewHolder{
TextView text;
public ViewHolderZero(View itemView) {
super(itemView);
text = (TextView)itemView.findViewById(R.id.tvItem0);
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder {
TextView text2;
public ViewHolderOne(View itemView) {
super(itemView);
text = (TextView)itemView.findViewById(R.id.tvItem1);
}
}
In my main Activity
I create LinkedList
and add elements with types "Item0" and "Item1":
LinkedList<Item> ll = new LinkedList<>();
ll.add(0, new Item0("abc"));
ll.add(1, new Item1("bca"));
I tried to use Comparator
:
class Comparation implements Comparator<Item> {
public int compare(Item0 lhs, Item1 rhs) {
if (lhs.getText() < rhs.getText()){
return 1;
}else return -1;
}
}
But it doesn't work because of wrong args in compare()
.
If I understand correctly, I can use Collections.sort()
and Comparator
for list, which consists of same-type elements. But how can I sort different-type elements?
You could make Item0
and Item1
subclasses of Item
(if they are not already).
getText()
should be a method of Item
(which Item1
and Item2
will inherit).
After that, you can compare them properly, since they are of the same type:
class Comparation implements Comparator<Item> {
public int compare(Item lhs, Item rhs) {
// your comparation logic
}
}