Skip to content

Instantly share code, notes, and snippets.

@whalemare
Last active February 19, 2018 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whalemare/9a565eb740345449a9f6080ac5025b0b to your computer and use it in GitHub Desktop.
Save whalemare/9a565eb740345449a9f6080ac5025b0b to your computer and use it in GitHub Desktop.
AttrsDelegate that can simply retrieve attrs for your custom widget
/**
* Helper in work with custom attributes on some widget
* <p>
* Just pass to this attributeSet from your widget constructor and {@link StyleableRes}
*
* @author Anton Vlasov - whalemare
* @since 2017
*/
public class AttrsDelegate {
private final TypedArray typedArray;
/**
* @param context for obtain styled attrs
* @param attributeSet set from your constructor.
* If you pass <b>null</b>, function {@link #apply(Invokable)} not be called!
* @param attrs your custom {@link StyleableRes}
*/
public AttrsDelegate(Context context,
@Nullable AttributeSet attributeSet,
@StyleableRes int[] attrs) {
if (attributeSet == null) {
typedArray = null;
} else {
typedArray = context.obtainStyledAttributes(attributeSet, attrs);
}
}
/**
* You can call this function only once.
* After that resources will be recycled
*
* @param action your function for apply some widget attrs
* @see TypedArray#recycle()
*/
public void apply(@NonNull Invokable<TypedArray> action) {
if (typedArray == null) return;
action.invoke(typedArray);
typedArray.recycle();
}
interface Invokable<T> {
void invoke(T t);
}
}
public class CustomView extends LinearLayout {
// call this method in your constructor
protected void setup(Context context, @Nullable AttributeSet attrs) {
AttrsDelegate attrsDelegate = new AttrsDelegate(context, attrs, R.styleable.TakePhotoWidget);
attrsDelegate.apply(widgetAttrs -> {
title = widgetAttrs.getString(R.styleable.TakePhotoWidget_title);
setTitle(title);
setMaxPhotosCount(widgetAttrs.getInteger(R.styleable.TakePhotoWidget_maxPhotosCount, 1));
setCounterEnabled(widgetAttrs.getBoolean(R.styleable.TakePhotoWidget_counterEnabled, false));
setEnabledImageViewer(widgetAttrs.getBoolean(R.styleable.TakePhotoWidget_imageViewerEnabled, true));
});
handleCounter(getPhotosCount(), getMaxPhotosCount());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment