我正在创建我的第一个应用程序(TO-DO),其中包含 RecyclerView 任务列表。我希望每个任务都有一个删除按钮,如图所示:
当我尝试添加onClickListener时,确实如此,但仅适用于位置0的项目。
这是适配器代码:
public class MainTabTasksAdapter extends RecyclerView.Adapter {
private ArrayList<Task> tasks;
private Context context;
public MainTabTasksAdapter(Context context, ArrayList<Task> data) {
tasks = data;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_task, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Task task = tasks.get(position);
ViewHolder holderCast = (ViewHolder) holder;
holderCast.taskTag.setText(task.getTag());
holderCast.taskTime.setText(task.getNiceDate());
holderCast.taskRepeat.setText(task.getNiceRepeatInterval());
// holderCast.task = task;
// holderCast.position = position;
}
@Override
public int getItemCount() {
return tasks.size();
}
private class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
Task task;
int position;
private TextView taskTag, taskTime, taskRepeat;
private ImageView btnTomorrow, btnEdit, btnDelete;
ViewHolder(View v) {
super(v);
taskTag = v.findViewById(R.id.task_tag);
taskTime = v.findViewById(R.id.task_time);
taskRepeat = v.findViewById(R.id.task_repeat);
btnDelete = v.findViewById(R.id.task_btnDelete);
btnDelete.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition(); // Thanks cricket_007
// tasks.remove(task);
tasks.remove(position);
notifyItemRemoved(position);
}
}
}
好的,问题是我在github上找到的floatingActionMenu。 即使在折叠模式下,它的大小在未折叠时也是相同的,并且在floatingActionButtons上发生了单击事件,但在按钮上没有。
答案 0 :(得分:0)
您不需要int position
。 (或Task task;
)
所有ViewHolder对象都有getAdapterPosition()
方法。
试试这个
@Override
public void onClick(View view) {
int position = getAdapterPosition();
tasks.remove(tasks.get(position));
notifyItemRemoved(position);
}
答案 1 :(得分:0)
尝试将此方法放在onBindViewHolder()
方法中,并从ViewHolder
类中删除onClick
holderCast.btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});