我们为什么要声明ViewHolder类是静态的?

时间:2017-05-15 06:06:03

标签: java android android-recyclerview recycler-adapter

我有以下的RecyclerViewAdapter类。下面的代码有什么奇怪的,如果我没有声明ViewHolder类是静态的,我会收到以下错误:

Error:(24, 8) error: MaterialRequiredListRecyclerViewAdapter is not abstract and does not override abstract method onBindViewHolder(MaterialRequiredListRecyclerViewAdapter.MaterialRequiredRecyclerViewHolder,int) in Adapter

但是,只要我将此类声明为静态,错误就会消失。

我知道声明ViewHolder类通过不允许内部类使用外部类的成员变量或将其自己的实例暴露给其他类来强制防止内存泄漏,但是我不知道了解上述错误的原因。

代码:

public class MaterialRequiredListRecyclerViewAdapter<T> extends RecyclerView.Adapter<MaterialRequiredListRecyclerViewAdapter.MaterialRequiredRecyclerViewHolder> {

    private int mLayoutFileId;
    private List<String> mMaterialRequiredDataList;
    private Context mContext;

    public MaterialRequiredListRecyclerViewAdapter(Context con, int layoutFileId, List materialRequiredList) {
        mContext = con;
        mLayoutFileId = layoutFileId;
        mMaterialRequiredDataList = materialRequiredList;
    }

    @Override
    public MaterialRequiredRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.
                from(parent.getContext()).
                inflate(mLayoutFileId, parent, false);//R.layout.layout_cardview_apointments_for_video_call_frag

        return new MaterialRequiredRecyclerViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MaterialRequiredRecyclerViewHolder holder, int position) {
        if(mMaterialRequiredDataList != null)
            holder.mMaterialRequiredTV.setText(mMaterialRequiredDataList.get(position));
    }

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

    public class MaterialRequiredRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.text_view_list_cell)
        TextView mMaterialRequiredTV;

        public MaterialRequiredRecyclerViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void onClick(View v) {

        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果你的问题是这样的:

  

我不明白上述错误的原因。

然后答案是将视图持有者类设置为静态使其可以从任何地方访问,而使其非静态使其仅通过其名称引用(如MaterialRequiredRecyclerViewHolder holder)无法访问。如果要保持非静态,只需更改适配器中的以下行:

@Override
public void onBindViewHolder(MaterialRequiredRecyclerViewHolder holder, int position) {
    if(mMaterialRequiredDataList != null)
        holder.mMaterialRequiredTV.setText(mMaterialRequiredDataList.get(position));
}

到此:

@Override
public void onBindViewHolder(MaterialRequiredListRecyclerViewAdapter.MaterialRequiredRecyclerViewHolder holder, int position) {
    if(mMaterialRequiredDataList != null)
        holder.mMaterialRequiredTV.setText(mMaterialRequiredDataList.get(position));
}

对非静态内部类的调用应该通过对外部类的引用。我很抱歉我的英语不好,但我希望我能解释一下。

答案 1 :(得分:0)

您必须公开视图持有者类中的所有方法。必须在适配器类中对其进行访问。如果您将其公开,则会出错。