How do I place new items at the top of a recyclerView?

后端 未结 2 923

I\'m adding content to my database (Firebase) which are suppose to be loaded into my recyclerview. But the new content always appear at the bottom of the re

相关标签:
2条回答
  • 2021-01-07 14:12

    I finally solved the issue all i needed to do was to initialize an integer variable as 0,add it along side with the object of the model class that is to be gotten from the Firebase database and finally notifying an item inserted to the adapter.The code will explain better

    int position = 0;
    ArrayList<Places> data = new ArrayList<>();
    LinearLayoutManager lg = new LinearLayoutManager(this);
    

    then the final code was this

    valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
    Places content = ds.getValue(Places.class);
        data.add(position,content);
    adapter = new YourAdapter(data, getApplicationContext);
          recyclerview.setLayoutManager(new Line);
          recyclerview.setAdapter(adapter);
          adapter.notifyItemInserted(position);
           adapter.notifyDataSetChanged();
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
         // Handle error code here
       }
         });
    
    0 讨论(0)
  • 2021-01-07 14:29

    If you want to appear new Items on the top just Add this code in your Activity. you need to reverse your RecyclerView, then you totally need this code segment. It does not require any modification or any special library. It’s so simple to work on LinearLayoutManager .

     LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
            mLayoutManager.setReverseLayout(true);
            mLayoutManager.setStackFromEnd(true);
            recyclerView.setLayoutManager(mLayoutManager);
    

    First you need to create a LinearLayoutManager object and use “setReverseLayout(true)” and “setStackFromEnd(true)” methods to reverse and add item at the end.

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