Why to use static with RecyclerView.ViewHolder [duplicate]

巧了我就是萌 提交于 2019-12-22 07:01:41

问题


Why is recommended to use static for a class extended from RecyclerView.ViewHolder if I create a new instance of this class on the onCreateViewHolder method and I guess that instance is used for each item:

@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:


Inner class contains reference to the outer class. So it means that every instance of your RecyclerView.ViewHolder will contain reference to your RecyclerView.Adapter.

By making it static you avoid keeping this reference.

Oracle Java Documentation - Nested Classes



来源:https://stackoverflow.com/questions/33702163/why-to-use-static-with-recyclerview-viewholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!