Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView - No animation on NotifyItemInsert

For some reason, when adding a new item to the RecyclerView (should be inserted to the top of the list), it won't show up unless I scroll down the list and back up to the top, and without any animation either. (Just appears at the top of the list as if it was there the whole time). Removing an item works fine with the proper 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 shows up immediately, but the RecyclerView will not scroll to the top of the list. (Manually have to scroll up to see it).

like image 375
Daniel Kim Avatar asked Jan 03 '15 18:01

Daniel Kim


2 Answers

This is happening because LinearLayoutManager thinks the item is inserted above the first item. This behavior makes sense when you are not at the top of the list but I understand that it is unintuitive when you are at the top of the list. We may change this behavior, meanwhile, you can call linearLayoutManager.scrollToPosition(0) after inserting the item if linearLayoutManager.findFirstCompletelyVisibleItemPosition() returns 0.

like image 189
yigit Avatar answered Nov 09 '22 10:11

yigit


I fix it using notifyItemChange first item. Just like this:

((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);
adapter.notifyItemChanged(0);
like image 3
chenupt Avatar answered Nov 09 '22 11:11

chenupt