RecyclerView - no animation on NotifyItemInsert

For some reason, when a new item is added to the RecyclerView (must be inserted at the top of the list), it will not be displayed unless I scroll down the list and go back up, and without any animation or. (It just appears at the top of the list, as if it was there all the time). Removing an item works great with related animations.

RecyclerViewAdapter:

@Override public void onNewDatabaseEntryAdded() { //item added to top of the list notifyItemInserted(0); } public FileViewerAdapter(Context context) { super(); mContext = context; mDatabase = new DBHelper(mContext); mDatabase.setOnDatabaseChangedListener(this); } 

SQLite Database:

 private static OnDatabaseChangedListener mOnDatabaseChangedListener; public static void setOnDatabaseChangedListener(OnDatabaseChangedListener listener) { mOnDatabaseChangedListener = listener; } public long addRecording(String recordingName, String filePath, long length) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(DBHelperItem.COLUMN_NAME_RECORDING_NAME, recordingName); cv.put(DBHelperItem.COLUMN_NAME_RECORDING_FILE_PATH, filePath); cv.put(DBHelperItem.COLUMN_NAME_RECORDING_LENGTH, length); cv.put(DBHelperItem.COLUMN_NAME_TIME_ADDED, System.currentTimeMillis()); long rowId = db.insert(DBHelperItem.TABLE_NAME, null, cv); if (mOnDatabaseChangedListener != null) { mOnDatabaseChangedListener.onNewDatabaseEntryAdded(); } return rowId; } 

LISTENER:

 public interface OnDatabaseChangedListener{ void onNewDatabaseEntryAdded(); void onDatabaseEntryRenamed(); } 

edit:

I should mention that if I use NotifyDataSetChanged instead of NotifyItemInserted, then the new item will appear immediately, but the RecyclerView will not scroll to the top of the list. (Manually need to scroll up to see it).

+7
android listener animation android-recyclerview android-adapter
source share
2 answers

This is because LinearLayoutManager considers the item to be pasted above the first item. This behavior makes sense when you are not at the top of the list, but I understand that it is not intuitive when you are at the top of the list. We can change this behavior, meanwhile you can call linearLayoutManager.scrollToPosition(0) after inserting the element if linearLayoutManager.findFirstCompletelyVisibleItemPosition() returns 0.

+16
source share

I will fix this using the notifyItemChange first element. Similar:

 ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0); adapter.notifyItemChanged(0); 
+2
source share

All Articles