Skip to content

Instantly share code, notes, and snippets.

@noties
Created November 17, 2014 10:03
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 noties/1dae4c8e420da8b9a811 to your computer and use it in GitHub Desktop.
Save noties/1dae4c8e420da8b9a811 to your computer and use it in GitHub Desktop.
Centered ScrollView
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;
/**
* Created by Dimitry Ivanov (noties.app@gmail.com) / macbook on 10/10/14.
*/
public class CenteredScrollView extends ScrollView {
public CenteredScrollView(Context context) {
super(context);
}
public CenteredScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenteredScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
final View child = getChildAt(0);
if (child == null) {
return;
}
final int childHeight = child.getMeasuredHeight();
final boolean isSmaller = b - t > childHeight;
if (!isSmaller) {
child.layout(l, t, r, t + childHeight);
return;
}
final int verticalOffset = ((b - t) - childHeight) / 2;
child.layout(l, t + verticalOffset, r, b - verticalOffset);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment