出于某种原因,当向 RecyclerView 添加一个新项目时(应该插入到列表的顶部),它不会显示,除非我向下滚动列表并返回到顶部,并且没有任何动画任何一个。 (只是出现在列表的顶部,就好像它一直都在那里一样)。使用适当的动画可以很好地移除项目。
回收 View 适配器:
@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 数据库:
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;
}
听众:
public interface OnDatabaseChangedListener{
void onNewDatabaseEntryAdded();
void onDatabaseEntryRenamed();
}
编辑:
我应该提到,如果我使用 NotifyDataSetChanged 而不是 NotifyItemInserted,那么新项目会立即显示,但 RecyclerView 不会滚动到列表顶部。 (必须手动向上滚动才能看到)。
最佳答案
发生这种情况是因为 LinearLayoutManager 认为该项目插入到第一个项目之上。当您不在列表顶部时,这种行为是有意义的,但我知道当您位于列表顶部时,这是不直观的。我们可能会更改此行为,同时,如果 linearLayoutManager.findFirstCompletelyVisibleItemPosition()
返回 0,您可以在插入项目后调用 linearLayoutManager.scrollToPosition(0)
。
关于android - RecyclerView - NotifyItemInsert 上没有动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757892/