因此,当我添加一个项目时,它不会为其设置动画,也不会滚动到正确的位置。但是,当我删除某些内容时,它会为对象移除设置动画。
以下是添加代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == NEWITEMREQUESTCODE && resultCode == Activity.RESULT_OK) {
// AFTER CREATING A NEW ITEM
OilChangeableItem oilChangeableItem = data.getParcelableExtra("oil_item");
// Add the new item and notify the dataset.
oilChangeableAdapter.notifyItemInserted(0);
items.add(0, oilChangeableItem);
} else if (requestCode == EDITITEMRESULTCODE && resultCode == Activity.RESULT_OK) {
// AFTER EDITING AN ITEM
OilChangeableItem oilChangeableItem = data.getParcelableExtra("oil_item");
// Replace the existing item at whatever position it was originally at and notify the dataset.
oilChangeableAdapter.notifyItemChanged(data.getIntExtra("item_position", 0));
items.set(data.getIntExtra("item_position", 0), oilChangeableItem);
}
}
以下是删除代码:
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_delete_title);
builder.setIcon(R.drawable.ic_action_warning);
builder.setMessage(R.string.dialog_delete_message);
builder.setPositiveButton(R.string.button_text_delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Removed the selected item
oilChangeableAdapter.notifyItemRemoved(oilChangeableAdapter.getSelectedViewPosition());
items.remove(oilChangeableAdapter.getSelectedViewPosition());
// Notify the user it has been removed.
Toast.makeText(getActivity(), R.string.toast_item_deleted, Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(R.string.button_text_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
mode.finish();
有没有人有任何想法?
答案 0 :(得分:8)
这是因为您要在当前可见项目的“上方”添加项目。
我理解这看起来很意外,如果你考虑第一个位置但如果RV显示5到10的项目并且在位置2添加了新项目,那么你真的不希望你的列表移动到4到9。
所以LinearLayoutManager保持这个简单,如果在列表的上方或下方添加一个项目,它就不会移动(这样UX就是一致的)。
如果您希望在将项目添加到位置0时显示位置0,请致电 添加项目后,recyclelerView.scrollToPosition(0)。我想你真正想要的是:
items.add(0, oilChangeableItem);
oilChangeableAdapter.notifyItemInserted(0);
if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
layoutManager.scrollToPosition(0);
}