Search code examples
androidbutterknife

Using Butterknife to inject an array of views


Currently I have this array of views:

ImageView activityImageViews[] = {
    (ImageView) rootView.findViewById(R.id.img_activity_1),
    (ImageView) rootView.findViewById(R.id.img_activity_2),
    (ImageView) rootView.findViewById(R.id.img_activity_3),
    (ImageView) rootView.findViewById(R.id.img_activity_4)
};

Is there a way I could use Butterknife to inject all those views? I need to keep them in an array (or in a way so I can iterate over them).


Solution

  • Currently it is possible to inject several views as array. From ButterKnife documentation (see VIEW LISTS section)

    @InjectViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
    List<EditText> nameViews;
    

    Same thing for multiple click listeners:

    @OnClick({ R.id.door1, R.id.door2, R.id.door3 })
    public void pickDoor(DoorView door) {
      if (door.hasPrizeBehind()) {
        Toast.makeText(this, "You win!", LENGTH_SHORT).show();
      } else {
        Toast.makeText(this, "Try again", LENGTH_SHORT).show();
      }
    }
    

    UPDATE 2017-09-19: Since Butterknife version Version 7.0.0 (2015-06-27) @Bind replaced @InjectView and @InjectViews. But since version Version 8.0.0 (2016-04-25) @Bind was replaced with @BindView and @BindViews for one view and multiple views, respectively. So for now the correct syntax is:

    @BindView(R.id.button1) Button button1;
    @BindView(R.id.button2) Button button2;
    
    @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
    List<EditText> nameViews;