0
我有一個包含5個項目的Arraylist。每個項目都有優先權。我想要做的是根據該優先級對這些項目進行排序。假設項目3的優先級爲100,那麼該項目應該先列在列表中。項目0的優先級爲-10,那麼該項目必須在列表中最後一個。我如何實現類似的東西? Adapterclass:根據int參數對RecyclerView數組中的項目進行排序
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;
}}