I am not able to draw the circle using Custom Views in Android. It just doesn't work, even though it is a basic code implementation, it is not working. Can someone help me for the same?
This is Custom View class implementation:
public class CustomView extends View {
private Paint paint;
private int color;
private float radius;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
color = ta.getColor(R.styleable.CustomView_circleColor, Color.BLACK);
radius = ta.getFloat(R.styleable.CustomView_circleSize, 200f);
ta.recycle();
init();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius, paint);
}
private void init() {
paint = new Paint();
paint.setColor(color);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
And this is my MainActivity implementation:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
This is attr.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="circleColor" format="color"></attr>
<attr name="circleSize" format="enum">
<enum name="small" value="100"></enum>
<enum name="medium" value="300"></enum>
<enum name="large" value="600"></enum>
</attr>
</declare-styleable>
</resources>
And this is activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hp.customviews.MainActivity">
<com.hp.customviews.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:circleColor="#009688"
app:circleSize="medium"
android:visibility="gone" />
</FrameLayout>
What am I doing wrong? Why my code is not working? Please help me with this.