在recyclerview中为checbox提供onclick监听器的位置

时间:2015-11-13 01:43:20

标签: android

我已经做到了这一点:

我在我的"数字"中创建了一个布尔变量。具有getter和setter的对象类。在我的适配器底部附近的bindNumbers方法中,我设置了复选框的选中状态。我知道我现在应该使用点击监听器,但我不知道如何实现这一目标。有人能给我一个关于现在做什么的初学者友好解释吗?论坛上的所有其他答案都更加先进,并没有帮助我。

public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> {

private List<numbers> mNumbers = Collections.emptyList();

public myAdapter (List<numbers> numbers) {
    mNumbers = numbers;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v  = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_slot, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
}


@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.bindNumbers(mNumbers.get(position));
}

@Override
public int getItemCount() {
    return mNumbers.size();
}


public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView numberText;
    EditText checklistText;
    Button deleteButton;
    CheckBox checkDisBox;

    public ViewHolder(View itemView) {
        super(itemView);
        numberText = (TextView) itemView.findViewById(R.id.number);
        checklistText = (EditText) itemView.findViewById(R.id.editText);
        deleteButton = (Button) itemView.findViewById(R.id.deleteButton);
        checkDisBox = (CheckBox) itemView.findViewById(R.id.checkBox);

        deleteButton.setOnClickListener(this);
    }

    public void bindNumbers(numbers numbers) {
        numberText.setText(numbers.getInt() + "");
        checkDisBox.setChecked(numbers.isChecked());
    }

    @Override
    public void onClick(View v) {
        mNumbers.remove(getAdapterPosition());
        notifyItemRemoved(getAdapterPosition());
    }
}
}

1 个答案:

答案 0 :(得分:0)

我通常在onBindViewHolder()方法中添加听众,即

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.bindNumbers(mNumbers.get(position));
    holder.checkDisBox.setOnClickListener(new OnClickListener({
        ...
    }));
}

编辑:

实施的简短帮助:在适配器中,添加:

public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> {

private List<numbers> mNumbers = Collections.emptyList();
private SparseBooleanArray mCheckedItems;

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.bindNumbers(mNumbers.get(position));
    boolean checked = mCheckedItems.get(position), false;
    holder.checkDisBox.setChecked(checked);
    holder.checkDisBox.setOnClickListener(new OnClickListener({
        mCheckedItems.put(position, !checked);
    }));
}