Viewholder Pattern in an Activity

Asked

Viewed 161 times

1

Let’s assume that I have an Activity with its layout and, using the Butterknife and the Viewholder Pattern, I create a nested class in which I pass 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 would pass the user class of Viewholder Pattern. Follow 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 point is:

1) Would creating such a standard for Activity be bad practice? This standard should only be used when "recycling" of Views is required?

2) Is passing a Viewholder as a parameter a bad practice? (assuming that in the auxiliary class I use all views within Viewholder)

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

  • In Verify login you use the views or their content?

  • I use both @ramaral

1 answer

1


1) Would creating such a standard for Activity be bad practice? This standard should only be used when "recycling" of Views is required?

The purpose of the Viewholder Standard is to avoid the repeated use of findViewById() for references to views.
It is usually referred to in the use of Listview/Recyclerview but can and is, in that sense/purpose, used in other situations.

When you declare Activity attributes to store views and use them to access them in places other than Activity, although you do not have a class for that purpose (Viewholder), you are effectively avoiding the repeated use of findViewById().

2) Is passing a Viewholder as a parameter a bad practice? (assuming that in the auxiliary class I use all views within Viewholder)

I don’t think so. It is common to use a class to group related information to avoid having to pass many parameters individually to a method.

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

How much would it be to cancel the Check login object. What matters is that the object, in this case Verify login, has a "lifespan" shorter than the Activity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.