Display new items at the top of a ListView

2019-02-09 02:37发布

I'm using a list to populate a ListView (). The user is able to add items to the list. However, I need the items to be displayed at the top of the ListView. How do I insert an item at the beginning of my list in order to display it in reverse order?

8条回答
对你真心纯属浪费
2楼-- · 2019-02-09 02:52

mBlogList is a recycler view...

mBlogList=(RecyclerView) findViewById(R.id.your xml file);
mBlogList.setHasFixedSize(true);


LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mBlogList.setLayoutManager(mLayoutManager);//VERTICAL FORMAT
查看更多
成全新的幸福
3楼-- · 2019-02-09 02:56

You could always have a datestamp in your objects and sort your listview based on that..

   public class CustomComparator implements Comparator<YourObjectName> {
        public int compare(YourObjectName o1, YourObjectName o2) {
            return o1.getDate() > o2.getDate() // something like that.. google how to do a compare method on two dates
        }
    }

now sort your list

Collections.sort(YourList, new CustomComparator()); 

This should sort your list such that the newest item will go on top

查看更多
三岁会撩人
4楼-- · 2019-02-09 02:57

The ListView displays the data as it is stored in your data source.

When you are adding in your database, it must be adding the elements in the end. So, when you are getting all the data via the Cursor object and assigning it to the ArrayAdapter, it is in that order only. You should basically be trying to put data in the beginning of the database, rather that in the end, by having some time-stamp maybe.

Using ArrayList, you can do it by Collections.reverse(arrayList) or if you are using SQLite, you can use order by.

查看更多
疯言疯语
5楼-- · 2019-02-09 03:01

You can add element at the beginning of the list: like

arraylist.add(0, object)

then it will always display the new element at the top.

查看更多
我命由我不由天
6楼-- · 2019-02-09 03:04

You should probably use an ArrayAdapter and use the insert(T, int) method.

Ex:

ListView lv = new ListView(context);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.id...);
lv.setAdapter(adapter);
...
adapter.insert("Hello", 0);
查看更多
\"骚年 ilove
7楼-- · 2019-02-09 03:12

You can always use a LinkedList instead and then use addFirst() method to add elements to your list and it will have the desired behaviour (new items at the top of the ListView).

查看更多
登录 后发表回答