Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AttributeLoader {
- private Optional<TypedArray> array = Optional.empty();
- private AttributeLoader(Context context, AttributeSet attrs, @StyleableRes int[] resources) {
- if (attrs != null && context != null && resources != null)
- array = Optional.of(context.obtainStyledAttributes(attrs, resources));
- }
- public static AttributeLoader of(Context context, AttributeSet attrs, @StyleableRes int[] resources) {
- return new AttributeLoader(context, attrs, resources);
- }
- public AttributeLoader drawable(@StyleableRes int resource, Consumer<Drawable> drawable) {
- return array.map(arr -> load(resource, drawable, arr::getDrawable)).orElse(this);
- }
- public AttributeLoader string(@StyleableRes int resource, Consumer<String> string) {
- return array.map(arr -> load(resource, string, arr::getString)).orElse(this);
- }
- public AttributeLoader integer(@StyleableRes int resource, Consumer<Integer> integer) {
- return array.map(arr -> load(resource, integer, resId -> arr.getInt(resId, 0))).orElse(this);
- }
- public AttributeLoader dimensionPixelSize(@StyleableRes int resource, Consumer<Integer> value) {
- return array.map(arr -> load(resource, value, resId -> arr.getDimensionPixelSize(resId, 0))).orElse(this);
- }
- private <T> AttributeLoader load(@StyleableRes int resource, Consumer<T> where, Function<Integer, T> injector) {
- try {
- where.accept(injector.apply(resource));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return this;
- }
- public void recycle() {
- array.ifPresent(TypedArray::recycle);
- }
- public AttributeLoader color(@StyleableRes int resource, int defaultColor, Consumer<Integer> color) {
- return array.map(arr -> load(resource, color, resId -> arr.getColor(resId, defaultColor))).orElse(this);
- }
- public AttributeLoader dimension(@StyleableRes int resource, float defaultDimension, Consumer<Float> dimension) {
- return array.map(arr -> load(resource, dimension, resId -> arr.getDimension(resId, defaultDimension))).orElse(this);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment