我无法在Android中使用自定义视图绘制圆圈。它只是不起作用,即使它是一个基本的代码实现,它也无法正常工作。有人可以帮助我吗?
这是Custom View类的实现:
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);
}
}
这是我的MainActivity实施:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
这是attr.xml文件:
<?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>
这是activity_main.xml文件:
<?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>
我做错了什么?为什么我的代码不起作用?请帮帮我。