如何从RecyclerView适配器返回数据?

时间:2016-08-12 12:40:27

标签: android android-recyclerview

我有一个RecyclerView,其中RecyclerView的每个对象都有一个复选框。每次按下其中一个复选框时,我想在适配器上插入数据。有一次我完成了(按片段上的一个按钮,将Adapter设置为RecyclerView),必须返回数据。

Adapter RecyclerView的代码(简化)是:

public List<CarItem> data; 
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyCustomViewHolder>  {

    public MyCustomAdapter(List<CarItem> data) {
        this.data=data;
    }

    public MyCustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout_car_item, parent, false);
        return new MyCustomViewHolder(view);
    }

    public void onBindViewHolder(final MyCustomViewHolder holder, final int position) {
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                  @Override
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                       //Here I add the data that I want to store
                       holder.getItem();
                  }
            });
    }

    public class MyCustomViewHolder extends RecyclerView.ViewHolder{
          public MyCustomViewHolder (View itemView) {
              super(itemView);
              //Here I make reference to all the elements of the layout of the Adapter
          }

          public void getItem(){
              Log.d("prove", "" + data.size());
          }
    }
}

我创建了getItem()方法来获取MyCustomViewHolder中的数据,但我不知道如何将数据返回到Fragment,我将Adapter设置为RecyclerView Adapter

是否有某种方法可以将数据从RecyclerView的{​​{1}}返回到我设置的Fragment

提前致谢!

3 个答案:

答案 0 :(得分:3)

更新回复:

使用CarItems列表的替代方案:

@OnClick(...)
public void onButtonClicked() {
    int size = ((MyCustomAdapter) mRecyclerView.getAdapter()).getItemCount();
    for (int i = 0; i < size; i++) {
        if (((MyCustomAdapter) mRecyclerView.getAdapter()).isItemChecked(i)) {
            // Get each selected item
            CarItem carItem = (MyCustomAdapter) mRecyclerView.getAdapter()).getItem(i);
            // Do something with the item like save it to a selected items array.
        }
    }
}

您还可以向适配器添加getCheckedItems()方法:

public List<CarItem> getCheckedItems() {
    List<CarItem> checkedItems = new ArrayList<>();
    for (int i = 0; i < getItemCount(); i++) {
        if (isItemChecked(i)) {
            checkedItems.add(getItem(i));
        }
    }
    return checkedItems;
}

并使用RecyclerView之类的内容:

((MyCustomAdapter) mRecyclerView.getAdapter()).getCheckedItems();
  

是否有某种方法可以从RecyclerView的适配器返回数据   到我设置它的片段?

一般来说,操纵片段中的数据:

将以下方法添加到适配器,并通过recyclerView从片段中调用它们,将其转换为自定义适配器:((MyCustomAdapter) mRecyclerView.getAdapter()).getItem(...);

public void setListItems(List<CarItem> data) {
    this.data = data;
}

public List getListItems() {
    return data;
}

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

public CarItem getItem(int position) {
    return data.get(position);
}

public void setItem(CarItem item, int position) {
    data.set(position, item);
}
  

我有一个RecyclerView,其中包含RecyclerView I的每个对象   有一个复选框。每次按下其中一个复选框我都会   喜欢在适配器上插入数据。

管理多重状态和已保存状态

阅读this explanation并查看this sample app for multichoice

This library还使用SparseBooleanArray扩展适配器以进行选择,以保存所选项目。

或者使用此选项保存已选中状态,并在按下按钮后使用它仅访问已检查项目的数据:

public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyCustomViewHolder>  {
    private ArrayList<CarItem> data;
    private SparseBooleanArray checkedState = new SparseBooleanArray();

    public void setCheckedState(int position, boolean checked) {
        checkedState.append(position, checked);
    }

    public boolean isItemChecked(int position) {
        return checkedState.get(position);
    }

    public SparseBooleanArray getCheckedState() {
        return checkedState;
    }

    public void onBindViewHolder(final MyCustomViewHolder holder, final int position) {
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                  @Override
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                       setCheckedState(holder.getAdapterPosition(), isChecked);
                       //Here I add the data that I want to store
                       if (isChecked) {
                           data.set(holder.getAdapterPosition(), holder.getItem());
                       } else {
                           data.set(holder.getAdapterPosition(), null);
                       }

              }
        });
}

Reason to use adapter position on this related Google I/O 2016 video

enter image description here

  

我创建了getItem()方法来获取内部数据   MyCustomViewHolder但我不知道如何将数据返回到   片段,我将适配器设置为RecyclerView。

向/从视图持有者设置/获取数据

这些方法也可用于获取数据,可能使用setTag()/ getTag()机制。

viewHolder.itemView.setTag(yourNewData);

/**
 * Returns this view's tag.
 *
 * @return the Object stored in this view as a tag, or {@code null} if not
 *         set
 *
 * @see #setTag(Object)
 * @see #getTag(int)
 */
@ViewDebug.ExportedProperty
public Object getTag() {
    return mTag;
}

/**
 * Sets the tag associated with this view. A tag can be used to mark
 * a view in its hierarchy and does not have to be unique within the
 * hierarchy. Tags can also be used to store data within a view without
 * resorting to another data structure.
 *
 * @param tag an Object to tag the view with
 *
 * @see #getTag()
 * @see #setTag(int, Object)
 */
public void setTag(final Object tag) {
    mTag = tag;
}
  

有一次我说完了(按一下   片段上的按钮,将适配器设置为RecyclerView)   必须退回数据。

我需要额外的信息,告诉您在返回数据时要做什么,以及在此处再次将适配器设置为recyclerview的原因。

findViewHolderForAdapterPosition(int)

/**
 * Return the ViewHolder for the item in the given position of the data set. Unlike
 * {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
 * adapter changes that may not be reflected to the layout yet. On the other hand, if
 * {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
 * calculated yet, this method will return <code>null</code> since the new positions of views
 * are unknown until the layout is calculated.
 * <p>
 * This method checks only the children of RecyclerView. If the item at the given
 * <code>position</code> is not laid out, it <em>will not</em> create a new one.
 *
 * @param position The position of the item in the data set of the adapter
 * @return The ViewHolder at <code>position</code> or null if there is no such item
 */
public ViewHolder findViewHolderForAdapterPosition(int position) {
    if (mDataSetHasChangedAfterLayout) {
        return null;
    }
    final int childCount = mChildHelper.getUnfilteredChildCount();
    for (int i = 0; i < childCount; i++) {
        final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
        if (holder != null && !holder.isRemoved() && getAdapterPositionFor(holder) == position) {
            return holder;
        }
    }
    return null;
}

@OnClick(...)
public void onButtonClicked() {
    int size = ((MyCustomAdapter) mRecyclerView.getAdapter()).getItemCount();
    for (int i = 0; i < size; i++) {
        ViewHolder vh = (MyCustomViewHolder) findViewHolderForAdapterPosition(i);
        if (vh != null && ((MyCustomAdapter) mRecyclerView.getAdapter()).isItemChecked(i)) {
            Object obj = vh.itemView.getTag();
            // Manipulate the data contained in this view holder
            // but perhaps would be better to save the data in the CarItem
            // and don't manipulate the VH from outside the adapter
        }
    }
}

答案 1 :(得分:0)

最简单的方法是使用EventBus https://github.com/greenrobot/EventBus

只需在您的片段中注册它并设置@Subscribe方法即可。 构建简单的类并使用EventBus.getDefault()将数据从适配器传递到片段.post(new YourClass(yourData));

另一种方法是使用intarfaces。

注意!

当您在适配器中使用复选框时,您必须记住复选框中的旧值,并在滚动列表时设置。那么您可能对SparseBooleanArray

感兴趣

答案 2 :(得分:-3)

请勿使用RecyclerView。它不是为了这种目的而设计的。当您希望在回收行时显示只读数据时,RecyclerViewListView非常有用。使用这些视图从用户获取输入是危险的,因为在滚动后回收行时可能会丢失已输入的数据。请改用LinearLayout。这样您就可以直接访问其中的视图。如果要显示的原始数据不是固定计数,则可以动态地将View添加到容器中。