2017-05-24 61 views
2

我有一個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

你嘗試'yourAdapter.notifyDatasetChanged()'? –

+1

你應該可以得到使用列表傳遞給適配器'filterList',如果在適配器中你正在修改項目,那麼'filterList'也會訪問(更新)項目 – Yazan

回答

1

添加下面的方法來您的適配器,並用它在你的活動像adapter.getSelection()

public List<Item> getSelection() { 

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

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