如何从RecyclerView获取修改后的数据?

时间:2017-05-24 09:10:07

标签: android android-recyclerview

我有一个 RecyclerView 来显示通过适配器传递的过滤器列表。此列表包含具有布尔值的项目,用于检查项目是否已按下。我需要将此数据返回给活动以获得已检查元素的列表。我怎么能做到这一点?

RecyclerView适配器

public class RvFilterAdapter extends BaseQuickAdapter<FilterSelectable, BaseViewHolder> {

    public RvFilterAdapter(int layoutResId, List data) {
        super(R.layout.filter_item, data);
    }

    @Override
    protected void convert(BaseViewHolder viewHolder, FilterSelectable item) {

        int position = viewHolder.getLayoutPosition();

        setupViews(viewHolder, item);
        setupListeners(viewHolder, item);

        Log.e("RV", "position=" + position + " i=" + item.getId() +" name=" + item.getName() + " checked=" + item.isSelected());

    }

    public void setupViews(BaseViewHolder baseViewHolder, FilterSelectable item){

        baseViewHolder
                .setText(R.id.tv_filter_name, item.getName())
                .setChecked(R.id.tbc_filter, item.isSelected())
                .addOnClickListener(R.id.ll_filter_root)
                .addOnClickListener(R.id.tbc_filter);

    }

    public void setupListeners(BaseViewHolder baseViewHolder, final FilterSelectable item){

        baseViewHolder.getView(R.id.tbc_filter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.isSelected()){
                    v.setSelected(false);
                    item.setSelected(false);
                }else{
                    v.setSelected(true);
                    item.setSelected(true);
                }
            }
        });

    }

}

FilterActivity

RvFilterAdapter filterAdapter = new RvFilterAdapter(this, R.layout.filter_item, filterList);
filterAdapter.openLoadAnimation();
recyclerView.setAdapter(filterAdapter);

如何修改我传递给适配器的filterList以保存活动和RecyclerView之间的更改?

谢谢

1 个答案:

答案 0 :(得分:1)

将以下方法添加到您的适配器,并在您的活动中使用它,如adapter.getSelection()

public List<Item> getSelection() {

    List<Item> selectedItems = new ArrayList<>();

    for(Item item: list) {
        if(item.isSelected()) {
           selectedItems.add(item);
        }
    }
    return selectedItems;
}