1.自定义控件
BallView类
public class BallView extends View {
private Paint mpaint;
private int x=100;
private int y=100;
private int r=100;
public BallView(Context context) {
this(context,null);
}
public BallView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public BallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//关联我们所声明的自定义属性
TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.BallView,defStyleAttr,0);
//获取属性
//获取内圆半斤
r = ta.getInt(R.styleable.BallView_ball_size,r);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画笔
mpaint = new Paint();
//设置画笔颜色
mpaint.setColor(Color.parseColor("#FF0000"));
mpaint.setAntiAlias(true);
//设置画布颜色
canvas.drawColor(Color.parseColor("#FFFFFF"));
//画圆
canvas.drawCircle(x,y,r,mpaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x=(int) event.getX();
y= (int) event.getY();
//System.out.println("按下时: " + "x坐标:" + event.getRawX() + " " + "y坐标:" + event.getRawY());
}
break;
case MotionEvent.ACTION_MOVE:
{
x=(int) event.getX();
y= (int) event.getY();
// System.out.println("移动时: " + "x坐标:" + event.getRawX() + " " + "y坐标:" + event.getRawY());
}
break;
case MotionEvent.ACTION_UP:
{
x=(int) event.getX();
y= (int) event.getY();
//System.out.println("抬起时: " + "x坐标:" + event.getRawX() + " " + "y坐标:" + event.getRawY());
}
break;
}
/*this.x= x;
this.y=y;*/
WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
int width = manager.getDefaultDisplay().getWidth();
int height = manager.getDefaultDisplay().getHeight();
postInvalidate();
return true;
}
}
2.在values中创建attrs.xml
自定义属性
<declare-styleable name="BallView">
<attr name="ball_size" format="integer"></attr>
</declare-styleable>
3.在布局中写控件及属性
xmlns:xxx="http://schemas.android.com/apk/res-auto"
<com.example.ballviewdemo.BallView
android:id="@+id/ball"
xxx:ball_size="30"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />