是否可以在列表视图中颠倒顺序? [英] Is it possible to reverse the order in a listview?

查看:69
本文介绍了是否可以在列表视图中颠倒顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从firebase实时数据库中获取数据时,数据会自动以升序列出,但是我试图将放入数组列表中的值以相反的顺序而不是升序列出.

When I get my data from the firebase realtime database it is automatically listed in ascending order, but I'm trying to get the values that I put into an arraylist to be listed in reverse order rather that ascending.

使用列表视图时是否可以对值进行逆序排序?
目前使用的代码是:

Is it possible to get a reverse order on values when working with a listview ?
Code in use at the moment is:

    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);}}

此代码的当前输出为:

John Doe VI - Steps: 0
John Doe III - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
John Doe IV - Steps: 88
John Doe II - Steps: 111

首选输出:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

在代码中添加Collections.reverse(arrayList);时,输出为:

When adding Collections.reverse(arrayList); to the code, the output is:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe III - Steps: 0
John Doe VI - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79

推荐答案

您可以在将ArrayList提供给ArrayAdapter之前将其反转:

You can reverse the ArrayList before providing it to the ArrayAdapter by doing so:

Collections.reverse(arrayList);

在您的情况下,复制arrayList,然后将其反转并将其传递给ArrayAdapter的构造函数:

In your case copy arrayList before reversing it and passing it to the ArrayAdapter's constructor:

ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );

否则,每次调用onDataChange()时,arrayList对象都将反转,并且其顺序也将变得混乱.

Otherwise the arrayList object will get reversed every time onDataChange() gets called and its order will get mixed up.

这篇关于是否可以在列表视图中颠倒顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆