The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.
Here is the code of custom TextView
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class CircularTextView extends TextView
{
private float strokeWidth;
int strokeColor,solidColor;
public CircularTextView(Context context) {
super(context);
}
public CircularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void draw(Canvas canvas) {
Paint circlePaint = new Paint();
circlePaint.setColor(solidColor);
circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
Paint strokePaint = new Paint();
strokePaint.setColor(strokeColor);
strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
int h = this.getHeight();
int w = this.getWidth();
int diameter = ((h > w) ? h : w);
int radius = diameter/2;
this.setHeight(diameter);
this.setWidth(diameter);
canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
super.draw(canvas);
}
public void setStrokeWidth(int dp)
{
float scale = getContext().getResources().getDisplayMetrics().density;
strokeWidth = dp*scale;
}
public void setStrokeColor(String color)
{
strokeColor = Color.parseColor(color);
}
public void setSolidColor(String color)
{
solidColor = Color.parseColor(color);
}
}
Then in your XML, give some padding and make sure its gravity is center
<com.app.tot.customtextview.CircularTextView
android:id="@+id/circularTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:gravity="center"
android:padding="3dp"/>
And you can set the stroke width
circularTextView.setStrokeWidth(1);
circularTextView.setStrokeColor("#ffffff");
circularTextView.setSolidColor("#000000");