Display new items at the top of a ListView

前端 未结 8 780
北恋
北恋 2021-01-02 06:28

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

相关标签:
8条回答
  • 2021-01-02 06:38

    By default list adds elements at bottom. That is why all new elements you add will show at bottom. If you want it in reverse order, may be before setting to listadapter/view reverse the list

    Something like:

    Collections.reverse(yourList);
    
    0 讨论(0)
  • 2021-01-02 06:38

    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

    0 讨论(0)
  • 2021-01-02 06:39

    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
    
    0 讨论(0)
  • 2021-01-02 06:40

    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);
    
    0 讨论(0)
  • 2021-01-02 06:48

    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.

    0 讨论(0)
  • 2021-01-02 06:53

    Another solution without modifying the original list, override getItem() method in the Adapter

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

    Updated: Example

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

    }

    0 讨论(0)
提交回复
热议问题