Reputation: 1649
I have a RecyclerView list of CardViews. New CardViews are inserted at the top of the list.
If the View is currently at the bottom of the CardView list and I click my "Add" button to create a new CardView, I want the RecyclerView to then show the new CardView at the top of the list. Currently, when the new CardView is created the RecyclerView just returns to the previous View at the bottom of the list.
I've tried many things, without any luck, including:
recyclerView.getLayoutManager().scrollToPosition(0);
recyclerView.scrollToPosition(0);
linearlayoutmanager.scrollToPositionWithOffset(0,0)
Adapter.java
public void add(Contact item) {
if (contactList.size()==0) {
contactList.clear();
notifyDataSetChanged();
}
contactList.add(item);
notifyItemInserted(0);
}
public void addAll(List<Contact> contactList) {
for (Contact contact : contactList) {
add(contact);
}
}
Activity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EmptyRecyclerView recyclerView = (EmptyRecyclerView)findViewById(R.id.list_recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setEmptyView(findViewById(R.id.empty_view));
contactListAdapter = new ContactListAdapter(this);
contactListAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(contactListAdapter);
@Override
protected void onStart() {
super.onStart();
loadData();
}
void loadData(){
List<Contact> contactList = new ArrayList<>();
Cursor cursor = sqLiteDB.retrieve();
Contact contact;
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
do {
contact = new Contact();
contact.setI(cursor.getInt(0));
contact.setC(cursor.getInt(1));
contact.setT(cursor.getString(2));
contact.setN1(cursor.getString(3));
contact.setN2(cursor.getString(4));
contact.setD(cursor.getString(5));
contact.setDt(cursor.getString(6));
contact.setTm(cursor.getLong(7));
// add the item to the top of the List.
contactList.add(0, contact);
} while (cursor.moveToNext());
}
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
contactListAdapter.clear();
contactListAdapter.addAll(contactList);
Upvotes: 1
Views: 1251
Reputation: 6297
do like this
recyclerview.post(new Runnable() {
@Override
public void run() {
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
layoutManager.scrollToPositionWithOffset(0, 0);
}
});
if this does not work check where are you calling this and control executes this statement or not.
Upvotes: 3
Reputation: 3563
I use this with a "scroll to top" button, you can try work your way around with it :
LinearLayoutManager mlayoutManager = (LinearLayoutManager) rv.getLayoutManager();
mlayoutManager.scrollToPositionWithOffset(0, 0);
Upvotes: 0