简体   繁体   English

在recyclerview中添加项目 - 错误的位置

[英]Adding item in recyclerview - wrong position

I've a function like this one: 我有一个像这样的功能:

private void addItem(final int position, Meals newMeal){
    if(isLeft(position)){
        Meals.add(position+2, newMeal);
    }
    else{
        Meals.add(position+1, newMeal);
    }
    notifyItemInserted(position);
}

Where I want to add a selected item (duplicate it) +2 positions (starting from current one) if it's left item (I've two columns) or +1 if it's right one. 我想要添加一个选定项目(复制它)+2个位置(从当前一个开始),如果它是左项(我有两列)或+1,如果它是正确的。 Right now, it just inserts items in wrong positions. 现在,它只是将项目插入错误的位置。 Any ideas what's wrong? 有什么想法有什么不对吗?

Maybe try the following: 也许尝试以下方法:

private void addItem(final int position, Meals newMeal){
    if(isLeft(position)){
        Meals.add(position+2, newMeal);
        notifyItemInserted(position+2);

    }
    else{
        Meals.add(position+1, newMeal);
        notifyItemInserted(position+1);
    }
}

According to RecyclerView.Adapter/#notifyItemInserted : 根据RecyclerView.Adapter /#notifyItemInserted

Notify any registered observers that the item reflected at position has been newly inserted. 通知任何注册观察员新插入的位置反映的项目。 The item previously at position is now at position position + 1. 先前在位置的项目现在位于+ 1的位置。

Hope it helps 希望能帮助到你

use .set() method instead of add 使用.set()方法而不是添加

For adding items, just append them to Meal and then go notifyDatasetChanged(). 要添加项目,只需将它们附加到Meal,然后转到notifyDatasetChanged()。 Another way to go is to use notifyItemRangeInserted(). 另一种方法是使用notifyItemRangeInserted()。 Depending on how are you adding new items and how many of them, it might be worth it. 根据您添加新项目的方式以及新项目的数量,这可能是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM