Skip to content

Instantly share code, notes, and snippets.

@rekire
Created December 23, 2016 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rekire/1acdb3c58ac9a8af432aac37e8950ced to your computer and use it in GitHub Desktop.
Save rekire/1acdb3c58ac9a8af432aac37e8950ced to your computer and use it in GitHub Desktop.
A small layout to observe measure calls to know when the layout dimentions are fixed.
public class MeasureCallbackLayout extends FrameLayout {
private final List<MeasureCallback> listeners = new ArrayList<>();
private int width = -1;
private int height = -1;
public MeasureCallbackLayout(Context context) {
super(context);
}
public MeasureCallbackLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MeasureCallbackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@SuppressLint("NewApi")
public MeasureCallbackLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public boolean addMeasureListener(MeasureCallback callback) {
return listeners.add(callback);
}
public boolean removeMeasureListener(MeasureCallback callback) {
return listeners.remove(callback);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if((MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY || MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) &&
MeasureSpec.getSize(widthMeasureSpec) != width && MeasureSpec.getSize(heightMeasureSpec) != height) {
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
for (int i = listeners.size() - 1; i >= 0; i--) {
listeners.get(i).onMeasured();
}
}
}
public interface MeasureCallback {
void onMeasured();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment