如何迭代recyclerview中的视图项?

时间:2015-08-01 09:35:14

标签: android

我有一个带有以下适配器的RecyclerView

public class DataTransferMeasureListAdapter extends DataTransferBaseListAdapter<DataTransferMeasureListAdapter.ViewHolder> {
    private Context context = null;
    private List<DataTransferListEntry> entries = null;

    public DataTransferMeasureListAdapter(Context context, List<DataTransferListEntry> entries) {
        super(context);

        this.context = context;
        this.entries = entries;
    }

    @Override
    public DataTransferMeasureListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.fragment_datatransfer_measure_list_row, parent, false);

        return new DataTransferMeasureListAdapter.ViewHolder(this.context, itemView);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final DataTransferMeasureListEntry entry = (DataTransferMeasureListEntry) entries.get(position);
        final ViewHolder viewHolder = (ViewHolder) holder;

        String time = Helper.getDateTimePattern(this.context, entry.getDate());
        String value = Helper.getMeasureValue(unit, entry.getValue());

        viewHolder.textViewTime.setText(time);
        viewHolder.textViewValue.setText(value);
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private Context context = null;
        private TextView textViewValue = null;
        private TextView textViewTime = null;

        public ViewHolder(Context context, View itemView) {
            super(itemView);

            this.context = context;

            this.textViewValue = (TextView) itemView.findViewById(R.id.datatransfer_measure_list_row_textview_value);
            this.textViewTime = (TextView) itemView.findViewById(R.id.datatransfer_measure_list_row_textview_time);
        }
    }
}

在我的ListView

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    this.adapter = new DataTransferMeasureListAdapter(this.getActivity(), this.dataTransferMeasureListEntries);
    this.listRowParent = (RecyclerView) view.findViewById(R.id.datatransfer_measure_list_row_parent);
    this.listRowParent.setAdapter(this.adapter);
    this.listRowParent.setLayoutManager(new LinearLayoutManager(this.getActivity()));
}

我现在需要迭代我的适配器中的每个Viewholder,以便我可以更改某些视图元素的可见性。我需要从适配器外部设置它。

我该怎么做?

1 个答案:

答案 0 :(得分:5)

正如@pskink在评论中所写。 实现这一目标的最快和最正确的方法是更改​​ entiries 数据,使其包含您将设置visibilty的值,然后从片段中更改这些值。如果一个数据条目已更改,则调用 notifyItemChanged ;如果一些数据条目已更改,则调用 notifyItemRangeChanged ;如果一切发生更改或发生零星更改,则调用 notifyDataSetChanged 。< / p>

你不希望片段调用适配器的方法,你只希望知道&#34;知道&#34;并操纵数据。