如何从android

时间:2017-06-05 14:44:37

标签: android android-recyclerview recycler-adapter

在我的应用程序中,我应该使用recyclerView并删除一些项目 我想删除recyclerview中的一些项目,为此,我在适配器中编写以下代码:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

        public ViewHolder(View itemView) {
            super(itemView);

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}

我想在运行此代码时删除项目:

holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });

但请告诉我错误

FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

如何修复此错误并从recyclerview删除项目?

6 个答案:

答案 0 :(得分:8)

试试吧,

int newPosition = holder.getAdapterPosition();

在你的removeItem()方法中,并使用newPosition重新定位。

喜欢,

  private void removeItem(int position) {
    int newPosition = holder.getAdapterPosition();
    model.remove(newPosition);
    notifyItemRemoved(newPosition);
    notifyItemRangeChanged(newPosition, model.size());
}

答案 1 :(得分:6)

我认为你应该拨打remove(holder.getAdapterPosition())而不是remove(position),因为当持有人的倒计时结束时,它可能已经改变了它的位置。

假设以下情况:

1º持有人 - &gt; 5秒倒计时

2º持有人 - &gt; 10秒倒计时

由于第二个持有者在第一个持有者之后完成,在10秒之后,remove(1)将被调用,但是,由于第一个持有者已经被移除,所以第二个持有者的位置将为0.因此,它应该调用{ {1}}代替remove(0)(这将导致remove(1))。

答案 2 :(得分:1)

删除Android中的Arraylist中的项目

holder.mRemoveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Get the clicked item label
                String itemLabel = mDataSet.get(position);
                // Remove the item on remove/button click
                mDataSet.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,mDataSet.size());
                // Show the removed item label`enter code here`
                Toast.makeText(mContext,"Removed : " + itemLabel,Toast.LENGTH_SHORT).show();

}

答案 3 :(得分:0)

如果您只想显示4项只需更改获取计数方法,则无需删除项目

 @Override
    public int getItemCount() {
        return (model.size()>4)?4:model.size();
    }

答案 4 :(得分:0)

如果少于四个项目,如果有超过四个项目和确切数量的项目,则只显示四个项目。然后,你可以使用它:

@Override
public int getItemCount() {
    int count = 0;
    if (model != null && model.size() > 0) {
        int listSize = model.size();
        if (listSize > 4) {
            count = 4;
        } else {
            count = listSize;
        }
    }
    return count;
}

答案 5 :(得分:0)

//////// set the position ////////

holder.tvTonightTimeCounter.setTag(position);

//////// remove item from recyclerview and arraylist ///////

holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                    @Override
                    public void onEnd(CountdownView cv) {
                    int positionToRemove = (int)view.getTag(); //get the position of view to delete stored in the tag
                    model.remove(positionToRemove);
                    notifyDataSetChanged();
                    }
                });