使用十字按钮从 RecyclerView 中删除项目
在 RecyclerView 适配器中,您需要处理十字按钮事件并删除相应的项目从数据集中。这是适配器的增强版本:
<code class="java">public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener { private ArrayList<String> mDataset; private static Context sContext; public MyAdapter(Context context, ArrayList<String> myDataset) { mDataset = myDataset; sContext = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false); ViewHolder holder = new ViewHolder(v); holder.mNameTextView.setOnClickListener(this); holder.mCrossButtonImageView.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.mNameTextView.setText(mDataset.get(position)); } @Override public int getItemCount() { return mDataset.size(); } @Override public void onClick(View view) { ViewHolder holder = (ViewHolder) view.getTag(); if (view.getId() == holder.mCrossButtonImageView.getId()) { int position = holder.getAdapterPosition(); mDataset.remove(position); notifyItemRemoved(position); Toast.makeText(sContext, "Item " + holder.mNameTextView.getText() + " has been removed from list", Toast.LENGTH_SHORT).show(); } } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView mNameTextView; public ImageView mCrossButtonImageView; public ViewHolder(View v) { super(v); mNameTextView = (TextView) v.findViewById(R.id.nameTextView); mCrossButtonImageView = (ImageView) v.findViewById(R.id.crossButton); } } }</code>
此代码向十字按钮添加一个 onClick 侦听器,该按钮在单击时会删除相应的项目。请注意,应使用 getAdapterPosition() 而不是 getPosition(),因为 getPosition() 现已弃用。
以上是如何使用十字按钮从 RecyclerView 中删除项目?的详细内容。更多信息请关注PHP中文网其他相关文章!