要在Android RecyclerView中实现滑动删除,并只在第一个元素上绘制图标,可以按照以下步骤进行操作:
private boolean showDeleteIcon = false;
public MyAdapter(List data) {
// 初始化适配器数据
}
public void setShowDeleteIcon(boolean showDeleteIcon) {
this.showDeleteIcon = showDeleteIcon;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView deleteIcon;
public MyViewHolder(View itemView) {
super(itemView);
deleteIcon = itemView.findViewById(R.id.delete_icon);
}
public void bindData(String item) {
// 绑定数据到ViewHolder中的视图
}
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String item = dataList.get(position);
holder.bindData(item);
if (position == 0 && showDeleteIcon) {
holder.deleteIcon.setVisibility(View.VISIBLE);
} else {
holder.deleteIcon.setVisibility(View.GONE);
}
}
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
// 使用ItemTouchHelper实现滑动删除
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
// 当第一个元素被滑动删除时,显示删除图标
if (viewHolder.getAdapterPosition() == 0) {
adapter.setShowDeleteIcon(true);
adapter.notifyDataSetChanged();
}
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
}
通过以上步骤,可以实现在Android RecyclerView中滑动删除,并且只在第一个元素上绘制图标。当第一个元素被滑动删除时,会显示删除图标。