androidandroid-canvasandroid-drawablexml-drawableshapedrawable

Drawing Circle programmatically using Android ShapeDrawable


I have a requirement in my project to draw a circle in runtime dynamically. So for that purpose I am using ShapeDrawable to create circle programmatically, but unfortunately I could not find any class or methods inside ShapeDrawable for CircleShape, instead I found only OvalShape(). So kindly please help me to draw a circle through ShapeDrawable by just passing diameter or radius of the circle. Thanks in advance. Any kind of customization would be useful for me to fix my solution.

Code I am using for ShapeDrawable is

public static ShapeDrawable drawCircle (Context context, int width, int height, int color) {

        //////Drawing oval & Circle programmatically /////////////

        ShapeDrawable oval = new ShapeDrawable (new OvalShape ());
        oval.setIntrinsicHeight (height);
        oval.setIntrinsicWidth (width);
        oval.getPaint ().setColor (color);
        return oval;
    }

Code using in MainActivity.java

if(Build.VERSION.SDK_INT >= 16) {
            txtCount.setBackground (Util.drawCircle (MainActivity.this, 50, 50, getResources ().getColor (R.color.yellow)));
            txtHotelCount.setText ("20");
        }else{
            txtCount.setBackgroundDrawable (Util.drawCircle (MainActivity.this, 50, 50, getResources ().getColor (R.color.yellow)));
            txtHotelCount.setText ("20");

        }

xml using for TextView txtCount in my project for is

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@color/white">

        <TextView
            android:id="@+id/txt_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_grey"
            android:gravity="center"
            android:textSize="12sp"
            android:padding="2dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_grey"
            android:text="AVAILABLE"
            android:layout_marginLeft="10dp"
            android:gravity="center"
            />
    </LinearLayout>

But still no luck even after setting the same width and height as 50. The property is behaving still like oval.


Solution

  • Give same height and width to your TextView

    <TextView
                android:id="@+id/txt_count"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:textColor="@color/text_grey"
                android:gravity="center"
                android:textSize="12sp"
                android:padding="2dp"
                />