Skip to content

Instantly share code, notes, and snippets.

@hanleyhansen
Created June 27, 2013 16:18
Show Gist options
  • Save hanleyhansen/8037f74304a32565228d to your computer and use it in GitHub Desktop.
Save hanleyhansen/8037f74304a32565228d to your computer and use it in GitHub Desktop.
package com.sourcetone;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class PageControl extends LinearLayout {
int page = 0;
int count = 0;
int spacer = 8;
private Boolean centered = true;
private final int r = 8;
private final Paint mNormal = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint mSelected = new Paint(Paint.ANTI_ALIAS_FLAG);
public PageControl(Context context) {
super(context);
setWillNotDraw(false);
}
public PageControl(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
setCentered(true);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
mNormal.setStyle(Style.FILL_AND_STROKE);
mNormal.setColor(getResources().getColor(R.color.indicatorInactiveFill));
mSelected.setStyle(Style.FILL_AND_STROKE);
mSelected.setColor(getResources().getColor(R.color.indicatorActiveFill));
}
public void setCentered(Boolean in) {
centered = in;
requestLayout();
invalidate();
}
public void setPage(int page) {
this.page = page;
invalidate();
}
public int getPage() {
return page;
}
public void setPageCount(int count) {
this.count = count;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (count <= 1)
return;
int d = r * 2;
int w = this.getWidth();
float left;
if (centered) {
left = ((w - ((d * count) + (spacer * (count - 1)))) / 2) + r;
} else {
left = r + 1;
}
for (int i = 0; i < count; i++) {
float x = left + (i * (d + spacer));
canvas.drawCircle(x, r + 1, r, (i + 1 == page) ? mSelected : mNormal);
}
}
}
@petetandon
Copy link

public static int dpToPx(Context context, int dp) {
        float density = getDensity(context);
    return (int) (dp * density + 0.5f);
}





private static Display getDefaultDisplay(Context context){
    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    return display;
}

public static float getDensity(Context context){

        DisplayMetrics metrics = new DisplayMetrics();
        getDefaultDisplay(context).getMetrics(metrics);
        return   metrics.density;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment