Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 431
aluxian Avatar asked Feb 17 '14 13:02

aluxian


2 Answers

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;
like image 186
Sneg Avatar answered Nov 13 '22 00:11

Sneg


I suppose that the elements added to the Array are dynamically, otherwise you can simply declare them in your header one by one and afterwards add them to the array:

// in the header:
@InjectView(R.id.imageview1) ImageView imageView1;
@InjectView(R.id.imageview2) ImageView imageView2;
@InjectView(R.id.imageview3) ImageView imageView3;

// inside your code:
ImageView activityImageViews[] = {
    imageView1, imageView2, imageView3
};

But however, if the elements are dynamic (in amount of elements/id of elements etc.) the only thing you can do is to use ButterKnife.findById which will spare the ImageView cast - you can't inject them via annotation because Butterknife does not know what to generate/inject on compile time (the information is first available on runtime).

ImageView activityImageViews[] = {
    ButterKnife.findById(view, R.id.img_activity_1),
    ButterKnife.findById(view, R.id.img_activity_2),
    ButterKnife.findById(view, R.id.img_activity_3),
    ButterKnife.findById(view, R.id.img_activity_4)
};
like image 29
Flixer Avatar answered Nov 13 '22 01:11

Flixer