xml布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/ra" 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.example.ballviewdemo.MainActivity"> <com.example.ballviewdemo.Myclass android:id="@+id/ball" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>class
package com.example.ballviewdemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * author:Created by WangZhiQiang on 2017/11/30. */ public class Myclass extends View { private float x = 20; private float y = 20; private float radio = 188; //画笔 private Paint a = new Paint(); Context context; public Myclass(Context context) { super(context); this.context=context; init(); } public Myclass(Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.context=context; init(); } public Myclass(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context=context; init(); } private void init() { a.setColor(Color.RED); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); a.setAntiAlias(true); canvas.drawCircle(x, y, radio, a); } @Override public boolean onTouchEvent(MotionEvent event) { this.x=(float) event.getX(); this.y= (float) event.getY(); invalidate(); return true; } }