當(dāng)我從 firebase 實(shí)時(shí)數(shù)據(jù)庫獲取數(shù)據(jù)時(shí),它會自動按升序列出,但我試圖讓我放入 arraylist 的值以相反的順序而不是升序列出。使用 listview 時(shí)是否可以對值進(jìn)行相反的排序?目前使用的代碼是: Query query = userRef.orderByChild("totalNumberOfSteps"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()) { String username = ds.child("username").getValue(String.class); long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class); Log.d(TAG , username + " - Steps: " + totalNumberOfSteps); arrayList.add(new String(username + " - " + "steps: " + totalNumberOfSteps)); arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , arrayList); listView.setAdapter(arrayAdapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.d(TAG , databaseError.getMessage()); //Don't ignore errors! } }; query.addListenerForSingleValueEvent(valueEventListener);}}此代碼的當(dāng)前輸出是:John Doe VI - Steps: 0John Doe III - Steps: 0John Doe V - Steps: 12John Doe I - Steps: 79John Doe IV - Steps: 88John Doe II - Steps: 111首選輸出:John Doe II - Steps: 111John Doe IV - Steps: 88John Doe I - Steps: 79John Doe V - Steps: 12John Doe III - Steps: 0John Doe VI - Steps: 0添加Collections.reverse(arrayList);到代碼時(shí),輸出為:John Doe II - Steps: 111John Doe IV - Steps: 88John Doe III - Steps: 0John Doe VI - Steps: 0John Doe V - Steps: 12John Doe I - Steps: 79
1 回答

肥皂起泡泡
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以在將 ArrayList 提供給 ArrayAdapter 之前反轉(zhuǎn)它:
Collections.reverse(arrayList);
arrayList在你的情況下,在反轉(zhuǎn)它并將它傳遞給 ArrayAdapter 的構(gòu)造函數(shù)之前復(fù)制:
ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );
否則,arrayList每次調(diào)用 onDataChange() 時(shí)對象都會被反轉(zhuǎn),并且它的順序會被混淆。
添加回答
舉報(bào)
0/150
提交
取消