RecycleView中列表上的最后一项位置错误

时间:2019-05-20 21:00:15

标签: android android-recyclerview

我正在创建要在其中显示RecycleView列表的Activity。 问题是当我尝试从列表中删除项目时。如果仅剩一项,则索引1而不是0。

如果我从最后开始删除项目,一切都会很好。但是,如果我删除从第一个项目到最后一个项目的项目,则会发生错误。 所以我有一个清单

Item1 - has index 0
Item2 - has index 1
Item3 - has index 2

删除项目1后:

Item2 - has index 0
Item3 - has index 1

删除项目2后:

Item2 - has index 1

您看到item2应该消失了,但是它在那里并且索引错误。

如果我使用notifyDataSetChanged();,则可以正确删除项目,但是无论我删除项目的顺序如何,列表中的名称从最后到第一个都消失了。

class MyLocationAdapter extends RecyclerView.Adapter {

    private List<Localization> localizations;
    private MyViewHolder myViewHolder;

    public MyLocationAdapter(List<Localization> localizations) {
        this.localizations = localizations;
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        myViewHolder = new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.location_item, parent, false));
        return myViewHolder;
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        String locationName = localizations.get(position).name;
        myViewHolder.name.setText(locationName);
        myViewHolder.addFavorite.setImageResource(R.drawable.ic_star_border_black_24dp);
        myViewHolder.deleteLocation.setImageResource(R.drawable.ic_delete_black_24dp);


        myViewHolder.deleteLocation.setOnClickListener(view -> {
            Log.d("Removed ", "" + localizations.get(position).name);
            localizations.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(0, getItemCount(), null);
        });
    }

如果我尝试删除索引错误且倒数第二个名称错误的最后一个项目,则会出现错误。有什么想法可以解决这个问题吗?

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.example.maciej.astroapp.Location.MyLocationAdapter$override.lambda$onBindViewHolder$1(MyLocationAdapter.java:48)
        at com.example.maciej.astroapp.Location.-$$Lambda$MyLocationAdapter$override$Yyi4W6TnKa-g0MRulbiyIxpVNZ0.onClick(lambda)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

1 个答案:

答案 0 :(得分:1)

position放在setOnClickListener内而不是holder.getAdapterPosition()