Created
December 1, 2015 12:51
-
-
Save fboldog/e79586abfb4a40b83fa9 to your computer and use it in GitHub Desktop.
Dead simple view injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.support.annotation.IdRes; | |
import android.view.View; | |
import java.lang.annotation.Annotation; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import java.lang.reflect.Field; | |
/** | |
* Usage: | |
* add as field: | |
* @ViewInjector.Inject(R.id.view_id) | |
* View view; | |
* | |
* in onCreate / getView / onCreateView | |
* ViewInjector.inject(this, viewRoot); | |
*/ | |
public final class ViewInjector { | |
public static void inject(Object object, Activity viewRoot) { | |
injectAsObject(object, viewRoot); | |
} | |
public static void inject(Object object, View viewRoot) { | |
injectAsObject(object, viewRoot); | |
} | |
private static void injectAsObject(Object object, Object viewRoot) { | |
for (final Field field : object.getClass().getFields()) { | |
for (final Annotation annotation : field.getDeclaredAnnotations()) { | |
if (annotation instanceof Inject) { | |
final int resourceId = ((Inject) annotation).value(); | |
final View view = findView(viewRoot, resourceId); | |
setView(object, field, view); | |
break; | |
} | |
} | |
} | |
} | |
private static View findView(Object viewRoot, int resourceId){ | |
if(viewRoot instanceof Activity){ | |
return ((Activity)viewRoot).findViewById(resourceId); | |
} else if (viewRoot instanceof View){ | |
return ((View)viewRoot).findViewById(resourceId); | |
} | |
throw new RuntimeException("viewRoot must be a Activity or View"); | |
} | |
private static void setView(Object object, Field field, View view){ | |
try { | |
field.set(object, view); | |
} catch (IllegalAccessException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.FIELD) | |
public @interface Inject { | |
@IdRes int value(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment