为什么要在RecyclerView.ViewHolder中使用static

时间:2015-11-13 21:35:16

标签: android android-recyclerview android-viewholder recycler-adapter

如果我在static方法上创建此类的新实例,为什么建议使用class来扩展RecyclerView.ViewHolder onCreateViewHolder,我猜这个实例是用于每个项目:

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview,parent,false);
    return new RecyclerViewAdapter.RecyclerViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {

    String textTop = noticias.get(position).getHora()+ noticias.get(position).getTemperatura();

    holder.textViewTop.setText(textTop);
    holder.textViewBot.setText(noticias.get(position).getTexto());

}


public static class RecyclerViewHolder extends RecyclerView.ViewHolder{

    public TextView textViewTop;
    public TextView textViewBot;

    public RecyclerViewHolder(View view){
        super(view);
        textViewTop = (TextView) view.findViewById(R.id.textView4);
        textViewBot = (TextView) view.findViewById(R.id.textView5);
    }

}

1 个答案:

答案 0 :(得分:16)

内部类包含对外部类的引用。因此,这意味着RecyclerView.ViewHolder的每个实例都会包含对您RecyclerView.Adapter的引用。

通过设置static,您可以避免保留此引用。

Oracle Java Documentation - Nested Classes