Skip to content

Instantly share code, notes, and snippets.

@STAR-ZERO
Last active December 14, 2015 16:29
Show Gist options
  • Select an option

  • Save STAR-ZERO/5115015 to your computer and use it in GitHub Desktop.

Select an option

Save STAR-ZERO/5115015 to your computer and use it in GitHub Desktop.
【Android RoboGuice】Adpate内のViewHolderでInjectView
public class SampleAdapter extends ArrayAdapter<String> {
...
...
// SuperViewHolderを継承する
static class ViewHolder extends SuperViewHolder {
@InjectView(R.id.text)
TextView text;
public ViewHolder(View v) {
super(v);
}
}
}
import java.lang.reflect.Field;
import java.util.ArrayList;
import javax.annotation.Nullable;
import roboguice.inject.InjectView;
import android.view.View;
public class SuperViewHolder {
private ArrayList<ViewMembersInjector> viewsForInjection;
public SuperViewHolder(View v) {
prepareFields();
injectViews(v);
}
private void prepareFields() {
viewsForInjection = new ArrayList<ViewMembersInjector>();
for (Field field : this.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(InjectView.class)) {
viewsForInjection.add(new ViewMembersInjector(field, field.getAnnotation(InjectView.class)));
}
}
}
private void injectViews(View v) {
for (ViewMembersInjector viewMembersInjector : viewsForInjection) {
viewMembersInjector.reallyInjectMembers(this, v);
}
}
class ViewMembersInjector {
private Field field;
private InjectView annotation;
public ViewMembersInjector(Field field, InjectView annotation) {
this.field = field;
this.annotation = annotation;
}
public void reallyInjectMembers(SuperViewHolder holder, View view) {
Object value = null;
try {
value = view.findViewById(annotation.value());
if (value == null && field.getAnnotation(Nullable.class) == null) {
throw new NullPointerException(String.format("Can't inject null value into %s.%s when field is not @Nullable", field.getDeclaringClass(), field.getName()));
}
field.setAccessible(true);
field.set(holder, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException f) {
throw new IllegalArgumentException(String.format("Can't assign %s value %s to %s field %s", value != null ? value.getClass() : "(null)", value, field.getType(), field.getName()));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment