Skip to content

Instantly share code, notes, and snippets.

@swissonid
Created September 7, 2016 10:40
Show Gist options
  • Save swissonid/8269bd1f66f1bbd1d0eea558f48e36c4 to your computer and use it in GitHub Desktop.
Save swissonid/8269bd1f66f1bbd1d0eea558f48e36c4 to your computer and use it in GitHub Desktop.
LayoutAnnotation
public abstract class BaseActivity extends AppCompatActivity {
@LayoutRes int getLayout() {
int layoutResId =-1;
Class screenType = getClass();
Layout layout = (Layout) screenType.getAnnotation(Layout.class);
if (layout == null) {
throw new IllegalArgumentException(
String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
screenType.getName()));
}
layoutResId = layout.value();
return layoutResId;
}
@Override protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
}
}
public abstract class BaseFragment extends Fragment {
protected @LayoutRes int getLayout() {
int layoutResId = Constants.NO_RESOURCE_KEY;
Class screenType = getClass();
Layout layout = (Layout) screenType.getAnnotation(Layout.class);
if (layout == null) {
throw new IllegalArgumentException(
String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
screenType.getName()));
}
layoutResId = layout.value();
return layoutResId;
}
@Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
mContentView = inflater.inflate(getLayout(), container, false);
return mContentView;
}
}
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Target(TYPE)
public @interface Layout {
int value();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment