Guest User

Untitled

a guest
Mar 20th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. public class AttributeLoader {
  2.     private Optional<TypedArray> array = Optional.empty();
  3.  
  4.     private AttributeLoader(Context context, AttributeSet attrs, @StyleableRes int[] resources) {
  5.         if (attrs != null && context != null && resources != null)
  6.             array = Optional.of(context.obtainStyledAttributes(attrs, resources));
  7.     }
  8.  
  9.     public static AttributeLoader of(Context context, AttributeSet attrs, @StyleableRes int[] resources) {
  10.         return new AttributeLoader(context, attrs, resources);
  11.     }
  12.  
  13.     public AttributeLoader drawable(@StyleableRes int resource, Consumer<Drawable> drawable) {
  14.         return array.map(arr -> load(resource, drawable, arr::getDrawable)).orElse(this);
  15.     }
  16.  
  17.     public AttributeLoader string(@StyleableRes int resource, Consumer<String> string) {
  18.         return array.map(arr -> load(resource, string, arr::getString)).orElse(this);
  19.     }
  20.  
  21.     public AttributeLoader integer(@StyleableRes int resource, Consumer<Integer> integer) {
  22.         return array.map(arr -> load(resource, integer, resId -> arr.getInt(resId, 0))).orElse(this);
  23.     }
  24.  
  25.     public AttributeLoader dimensionPixelSize(@StyleableRes int resource, Consumer<Integer> value) {
  26.         return array.map(arr -> load(resource, value, resId -> arr.getDimensionPixelSize(resId, 0))).orElse(this);
  27.     }
  28.  
  29.     private <T> AttributeLoader load(@StyleableRes int resource, Consumer<T> where, Function<Integer, T> injector) {
  30.         try {
  31.             where.accept(injector.apply(resource));
  32.         } catch (Exception e) {
  33.             e.printStackTrace();
  34.         }
  35.         return this;
  36.     }
  37.  
  38.     public void recycle() {
  39.         array.ifPresent(TypedArray::recycle);
  40.     }
  41.  
  42.     public AttributeLoader color(@StyleableRes int resource, int defaultColor, Consumer<Integer> color) {
  43.         return array.map(arr -> load(resource, color, resId -> arr.getColor(resId, defaultColor))).orElse(this);
  44.     }
  45.  
  46.     public AttributeLoader dimension(@StyleableRes int resource, float defaultDimension, Consumer<Float> dimension) {
  47.         return array.map(arr -> load(resource, dimension, resId -> arr.getDimension(resId, defaultDimension))).orElse(this);
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment