Android RecyclerView 專案刪除與新增
Android RecyclerView 提供了一種有效的方法來顯示大型資料集並處理專案插入和刪除。本文示範如何處理 RecyclerView 中的項目新增和刪除,重點放在具有 TextView 和十字按鈕 ImageView 的場景。
問題:
一個帶有 TextView 的 RecyclerView顯示項目列表,每個項目都有一個名稱和一個十字按鈕。按下十字按鈕應刪除對應的項目。
解決方案:
<code class="java">public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { 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) { // Create a view and ViewHolder ViewHolder holder = new ViewHolder(v); holder.mNameTextView.setOnClickListener(this); holder.mNameTextView.setOnLongClickListener(this); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { // Bind data to the ViewHolder holder.mNameTextView.setText(mDataset.get(position)); } @Override public int getItemCount() { return mDataset.size(); } @Override public void onClick(View view) { // Handle click events for the TextView Toast.makeText(sContext, holder.mNameTextView.getText(), Toast.LENGTH_SHORT).show(); } @Override public boolean onLongClick(View view) { // Handle long-click events for the TextView mDataset.remove(holder.getPosition()); notifyDataSetChanged(); return false; } 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>
<code class="java">@Override public void onClick(View v) { // Check if the view clicked is the cross button if (v.equals(holder.mCrossButtonImageView)) { // Remove the item from the dataset mDataset.remove(holder.getPosition()); // Notify the adapter of the item removal notifyItemRemoved(holder.getPosition()); } else { // Handle other click events if needed } }</code>
<code class="java">@Override public void onBindViewHolder(ViewHolder holder, int position) { // Bind data to the ViewHolder holder.mNameTextView.setText(mDataset.get(position)); // Check if the cross button should be visible if (itemClicked) { holder.mCrossButtonImageView.setVisibility(View.VISIBLE); } else { holder.mCrossButtonImageView.setVisibility(View.GONE); } }</code>
以上是如何使用十字刪除按鈕在 Android RecyclerView 中刪除和新增項目?的詳細內容。更多資訊請關注PHP中文網其他相關文章!