我有一个包含5个项目的Arraylist。每个项目都有优先权。我想要做的是根据优先级对这些项目进行排序。假设项目3的优先级为100,那么该项目应该在列表中排在第一位。项目0的优先级为-10,那么该项目必须在列表中排在最后。我该如何实现类似的东西? Adapterclass:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.cardViewHolder> {
private ArrayList<Card> item;
public CardAdapter(ArrayList<Card> item){
this.item = item;
}
@Override
public cardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout,parent,false);
cardViewHolder card = new cardViewHolder(v);
return card;
}
@Override
public void onBindViewHolder(cardViewHolder holder, int position) {
holder.titel.setText(item.get(position).getTitel());
holder.card_icon.setImageResource(item.get(position).getIcon());
holder.load_more.setText("Load more");
}
@Override
public int getItemCount() {
return item.size();
}
public static class cardViewHolder extends RecyclerView.ViewHolder{
TextView titel;
ImageView card_icon;
TextView load_more;
public cardViewHolder(View itemView){
super(itemView);
titel = (TextView)itemView.findViewById(R.id.titel);
card_icon = (ImageView)itemView.findViewById(R.id.card_icon);
load_more = (TextView)itemView.findViewById(R.id.loadmore);
}
}}
主要课程
public class MainActivity extends ActionBarActivity {
private RecyclerView recycler;
private RecyclerView.LayoutManager lmanager;
private RecyclerView.Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Card> data = new ArrayList<Card>();
data.add(new Card(R.drawable.mensa, "Mensa", "mensa"));
data.add(new Card(R.drawable.book, "Bibliothek", "bibliothek"));
data.add(new Card(R.drawable.timetable, "Stundenplan", "timetable"));
data.add(new Card(R.drawable.message, "Mitteilungen", "mitteilungen"));
data.add(new Card(R.drawable.noten, "Noten", "noten"));
recycler = (RecyclerView)findViewById(R.id.recycler);
lmanager = new LinearLayoutManager(this);
recycler.setLayoutManager(lmanager);
adapter = new CardAdapter(data);
recycler.setAdapter(adapter);
}}
卡类
public class Card {
private String titel;
private int card_icon;
private String id;
private int priority;
public Card(int icon, String titel, String id) {
this.card_icon = icon;
this.titel = titel;
this.id = id;
priority=0;
}
public String getTitel() {
return titel;
}
public int getIcon() {
return card_icon;
}
public String getId() {
return id;
}
public void setPriority(int priority){
this.priority = priority;
}}
答案 0 :(得分:0)
将优先级添加到卡片对象。例如
data.add(new Card(id, name, description, priority);
使用自定义Comparator
对arraylist进行排序。例如。
public class CustomComparator implements Comparator<Card> {
@Override
public int compare(Card card1, Card card2) {
Integer priority1 = card1.getPriority();
Integer priority2 = card2.getPriority();
return priority2.compareTo(priority1);
}
}
Collections.sort(data, new CustomComparator());