10

我正在使用列表来填充 ListView ()。用户能够将项目添加到列表中。但是,我需要将项目显示在 ListView 的顶部。如何在列表的开头插入一个项目以便以相反的顺序显示它?

4

8 回答 8

20

默认情况下,列表在底部添加元素。这就是为什么您添加的所有新元素都将显示在底部的原因。如果您希望它以相反的顺序排列,可能在设置为 listadapter/view 反转列表之前

就像是:

Collections.reverse(yourList);
于 2012-08-31T19:19:08.570 回答
15

另一种不修改原始列表的解决方案,覆盖Adapter中的getItem()方法

@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

更新:示例

public class ChatAdapter extends ArrayAdapter<ChatItem> {
public ChatAdapter(Context context, List<ChatItem> chats) {
    super(context, R.layout.row_chat, chats);
}

@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.row_chat, parent, false);
    }

    ChatItem chatItem = getItem(position);
    //Other code here

    return convertView;
}

}

于 2014-06-13T11:59:35.180 回答
10

您可能应该使用ArrayAdapterand 使用该insert(T, int)方法。

前任:

ListView lv = new ListView(context);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.id...);
lv.setAdapter(adapter);
...
adapter.insert("Hello", 0);
于 2012-08-31T19:40:47.150 回答
3

ListView 显示存储在数据源中的数据。

当您在数据库中添加时,最后必须添加元素。因此,当您通过 Cursor 对象获取所有数据并将其分配给 ArrayAdapter 时,它仅按该顺序排列。您基本上应该尝试将数据放在数据库的开头,而不是最后,可能有一些时间戳。

使用 ArrayList,你可以通过Collections.reverse(arrayList)或者如果你使用 SQLite,你可以使用order by.

于 2012-08-31T19:20:16.100 回答
3

您可以在列表的开头添加元素:like

arraylist.add(0, object)

那么它将始终在顶部显示新元素。

于 2017-12-04T05:38:03.863 回答
1

mBlogList 是一个回收站视图...

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
于 2017-09-29T17:22:52.170 回答
0

您始终可以使用 LinkedList 代替,然后使用 addFirst() 方法将元素添加到列表中,它将具有所需的行为(ListView 顶部的新项目)。

于 2013-04-29T11:27:02.490 回答
0

你总是可以在你的对象中有一个日期戳,并根据它对你的列表视图进行排序..

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

现在对您的列表进行排序

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

这应该对您的列表进行排序,以使最新的项目排在最前面

于 2012-08-31T19:50:04.067 回答