有没有得到从适配器父RecyclerView参考的更好的办法?

问题描述 投票:59回答:2

我在我需要从适配器内部到父RecyclerView的参考,特别是onBindViewHolder方法内的使用情况。到目前为止,我所要做的是将其分配给沿onCreateViewHolder ARG通过像这样的viewGroup parent方法私有类成员:

private ViewGroup mParent;

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // inflater logic.
    mParent = parent;
}

并引用在这样RecyclerViewonBindViewHolder

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // binder logic.
    ((RecyclerView)mParent).blahBlahBlah();
}

是否有这样做的更好的办法?也许RecyclerView.Adapter有,我可能已经错过了呢?

android android-adapter android-recyclerview
2个回答
169
投票

实际上,有以该重视的适配器RecyclerView callsback的具体方法。只是重写onAttachedToRecylerView(RecyclerView recyclerView)方法。

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

    RecyclerView mRecyclerView; 


    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        mRecyclerView = recyclerView;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        mRecyclerView....
    }

3
投票

另一种方式是在构造函数传递一个参考,例如

public final class MyAdapter extends RecyclerView.Adapper {
    private final recyclerView;

    public MyAdapter(@NonNull RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    ...

    @Override
     public void onBindViewHolder(ViewHolder holder, int position) {
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.