Skip to content

Instantly share code, notes, and snippets.

@vitovalov
Created June 5, 2018 08:46
Show Gist options
  • Save vitovalov/7b5787f00273cafd7972e591ed1d8eb8 to your computer and use it in GitHub Desktop.
Save vitovalov/7b5787f00273cafd7972e591ed1d8eb8 to your computer and use it in GitHub Desktop.
Android Divider custom view 1dp x fullwidth
public class Divider extends View {
private Paint paint;
private int width;
private float density;
public Divider(Context context) {
super(context);
init(context);
}
public Divider(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public Divider(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
density = getResources().getDisplayMetrics().density;
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.parseColor("#a7a6ab"));
paint.setAlpha(63); // 25%
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = dpToPx(200);
int desiredHeight = dpToPx(1);
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;
}
this.width = width;
setMeasuredDimension(width, desiredHeight);
}
private int dpToPx(int dp) {
return (int) (density * dp);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(0, 0, width, dpToPx(1), paint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment