使用十字按鈕從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中文網其他相關文章!