Skip to content

Instantly share code, notes, and snippets.

@alxscms
Created February 8, 2015 18:34
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 alxscms/89403087dacd61ab8998 to your computer and use it in GitHub Desktop.
Save alxscms/89403087dacd61ab8998 to your computer and use it in GitHub Desktop.
An abstract view simplifying the creation of Android widgets by scaling the canvas to the right size (following the device density), translating it following the set padding and by taking into account the view padding in the measurements
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public abstract class AbstractView extends View {
private float mOffsetX;
private float mOffsetY;
public AbstractView(Context context) {
super(context);
}
public AbstractView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AbstractView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected float getmOffsetX() {
return mOffsetX;
}
protected float getmOffsetY() {
return mOffsetY;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
float screenDensity = getResources().getDisplayMetrics().density;
int independentWidth = Math.round(screenDensity * calculateDesiredWidth());
int independentHeight = Math.round(screenDensity * calculateDesiredHeight());
int desiredWidth = independentWidth + getPaddingLeft() + getPaddingRight();
int desiredHeight = independentHeight + getPaddingTop() + getPaddingBottom();
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(desiredWidth, widthSize);
} else {
width = desiredWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(desiredHeight, heightSize);
} else {
height = desiredHeight;
}
mOffsetX = getPaddingLeft() / screenDensity;
mOffsetY = getPaddingTop() / screenDensity;
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
float screenDensity = getResources().getDisplayMetrics().density;
canvas.scale(screenDensity, screenDensity);
canvas.translate(mOffsetX, mOffsetY);
}
protected abstract float calculateDesiredWidth();
protected abstract float calculateDesiredHeight();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment