ViewHolder Pattern in an Activity

1

Suppose I have an Activity with its layout and, using ButterKnife and the ViewHolder Pattern, I create a nested class in which I step the View root and inject the ButterKnife in it. The goal would be for example, instead of passing View by View to an auxiliary class, I passed the ViewHolder Pattern user class. Here is an example:

public class LoginActivity extends AppCompatActivity {

    private ViewHolder viewHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        viewHolder = new ViewHolder(findViewById(R.id.layout_raiz));

        // faz algumas tarefas que poderiam deixar o código
        // da Activity sujo
        new VerificarLogin(viewHolder);
    }

    static class ViewHolder {
        @BindView(R.id.et1)
        EditText email;
        @BindView(R.id.et2)
        EditText senha;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

The question is:

1) Would creating such a standard for Activity be a bad practice? Should this be used only when it was necessary to "recycle" Views?

2) Passing a ViewHolder as a parameter is a bad practice? (assuming that in the helper class I use all views within the ViewHolder)

3) Using this type of practice in Activity, and passing as a parameter (as in the example above), should I configure the viewHolder = null object when the Activity was destroyed?

    
asked by anonymous 19.01.2018 / 18:39

1 answer

1
  

1) Would creating such a standard for Activity be a bad practice? Should this be used only when it was necessary to "recycle" Views?

The purpose of the ViewHolder Pattern is to avoid repeated use of findViewById() to get references to views. It is usually referred to in the use of ListView / RecyclerView but can and is in this sense / purpose used in other situations.

When you declare Activity attributes to save views and use them to access them in different places, even though you do not have a ViewHolder class, you are effectively avoiding repeated use of findViewById() .

  

2) Passing a ViewHolder as a parameter is a bad practice? (assuming that in the helper class I use all views within the ViewHolder)

I do not think so. It is common to use a class to group information that relates to avoid having to individually pass many parameters to a method.

  

3) Using this type of practice in Activity, and passing as a parameter (as in the example above), should I set the object viewHolder = null when Activity was destroyed?

How much would you void the VerifyLogin object. What matters is that the object, in this case VerifyLogin, has a lower "lifetime" than Activity.

    
20.01.2018 / 13:47