第一步:在values文件下下创建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCircle">
<attr name="radius" format="integer"/>
<attr name="mycolor" format="reference|color"/>
</declare-styleable>
</resources>
第二步:在layout.xml文件中声明一个自定义空间
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:myattr="http://schemas.android.com/apk/res/com.example.mycircle"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
第三部:创建自定义控件
public class MyCircle extends View {
private float currentx=50;
private float currenty=50;
private int radius;
public MyCircle(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCircle);
radius = ta.getInt(R.styleable.MyCircle_radius,0);
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(currentx, currenty, radius, paint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
currentx=event.getX();
currenty=event.getY();
invalidate();
return true;
}
}
第四步:创建自定义控件
<com.example.myview.MyCircle
android:id="@+id/circle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myattr:radius="50"
/>