Why to use static with RecyclerView.ViewHolder [du

2019-05-01 13:10发布

问题:

This question already has an answer here:

  • What difference between static and non static viewholder in RecyclerView Adapter? 2 answers

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