可拖动自定义view

首先,定义一个类,继承view,实现一个构造器,里面设置的属性是在values一个自定义的attrs中定义的,

public class CircleView extends View {
    private  float circle_x;
    private  float circle_y;
    private  float circle_radius;
    private  Paint paint;

    public CircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //找到设定好的attrs中的xml
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        //设置圆心的x,如果没有在xml中设置,就使用后面的默认值
        circle_x = a.getDimension(R.styleable.CircleView_circle_x, 50);
//设置圆心的Y        circle_y = a.getDimension(R.styleable.CircleView_circle_y, 50);
        //设置圆的颜色
        int color = a.getColor(R.styleable.CircleView_circle_color, Color.BLUE);
//设置圆的半径
        circle_radius = a.getDimension(R.styleable.CircleView_circle_radius, 30);



        a.recycle();
        //设置画笔
        paint = new Paint();
        //设置颜色
        paint.setColor(color);
        //设置实心或者空心圆
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        //设置空心圆的边线的宽度
        paint.setStrokeWidth(10);



    }
    //绘制画布
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制圆
        canvas.drawCircle(circle_x,circle_y,circle_radius,paint);

    }

    //使定义好的可以拖动,需要重写方法,监听屏幕的点击
     @Override
    public boolean onTouchEvent(MotionEvent event) {
       //得到点击的xy,可以查找一个freenDAO
         circle_x=event.getX();
        circle_y= event.getY();
         Log.e("------","circle_x"+circle_x+"  circle_y"+circle_y);
   invalidate();
         return true;
     }
}

在values中创建一个attrs.xml,用来放属性

<resources>
    <!--名字与自定义view的类名一样-->
    <declare-styleable name="CircleView">
        <!--自定义圆的颜色-->
        <attr name="circle_color" format="color"></attr>
        <!--自定义颜色的半径-->
        <attr name="circle_radius" format="dimension"></attr>
        <!--圆心x-->
        <attr name="circle_x" format="dimension"></attr>
        <!--圆心y-->
        <attr name="circle_y" format="dimension"></attr>
    </declare-styleable>

</resources>
然后在需要的布局中调用就可以了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值