Android - How To Define A Configurable Size Shape
Solution 1:
You cannot change the innerRadius
attribute programmatically, as it's only read from XML attributes when inflating (see for example this answer).
However, you could achieve more or less the same effect programmatically, by using a custom drawable to draw the ring. For example:
public class RoundBorderDrawable extends GradientDrawable
{
private static final int RING_THICKNESS = 20;
private static final int PADDING = 8;
private static final int NORMAL_COLOR = Color.BLUE;
private static final int PRESSED_COLOR = Color.RED;
private Paint mPaint;
public RoundBorderDrawable()
{
mPaint = new Paint();
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(RING_THICKNESS);
mPaint.setColor(NORMAL_COLOR);
}
@Override
public boolean isStateful()
{
return true;
}
@Override
protected boolean onStateChange(int[] stateSet)
{
boolean result = super.onStateChange(stateSet);
int color = NORMAL_COLOR;
for (int i = 0; i < stateSet.length; i++)
{
if (stateSet[i] == android.R.attr.state_pressed)
color = PRESSED_COLOR;
}
if (color != mPaint.getColor())
{
mPaint.setColor(color);
invalidateSelf();
result = true;
}
return result;
}
@Override
public void draw(Canvas canvas)
{
super.draw(canvas);
int diameter = Math.min(canvas.getWidth(), canvas.getHeight()) - RING_THICKNESS - 2 * PADDING;
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, diameter / 2, mPaint);
}
}
This will draw a circle that fits inside the Button
dimensions (I assumed you wanted to draw a circle even for non-square buttons).
Then just set a new instance of RoundBorderDrawable
as the background of your button (the properties that are constants in this example could, of course, be supplied via the constructor or with setter methods).
Solution 2:
I have a better approach for doing this. Instead of Ring
use Oval
and give stroke with color white and width @dimen/big_ring_button_thickness
but this doesn't give you circular shape. To achieve circular shape your button should be square, I mean width and height of the button should be same.
Post a Comment for "Android - How To Define A Configurable Size Shape"