Custom view * is not using the 2- or 3-argument View constructors; XML attributes will not work

在学习疯狂android 讲义第三版时,做一个实例跟随手指的小球

里面需要创建自定义View(DrawView)并在XML中使用,在最后运行的过程会报错。

先贴不完整代码:

class DrawView extends View{
    public float currentX =40;
    public float currentY=50;
    //创建画笔
    Paint p=new Paint();
    public DrawView(Context context)
    {
        super(context);
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        p.setColor(Color.RED);
        //绘制一个圆点(作为小球)
        canvas.drawCircle(currentX,currentY,15,p);
    }

    //为该组件的触碰事件重写时间处理方法
    @Override
    public boolean onTouchEvent(MotionEvent event){
        //修改x,y操作
        currentX =event.getX();
        currentY= event.getY();
        //通知当前组件重绘自己
        invalidate();
        return true;
    }
}

XML代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.crazyit.test.interface15Activity"
    android:id="@+id/rlRoot">

    <org.crazyit.test.DrawView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

这时点到Design界面时会提示Custom view * is not using the 2- or 3-argument View constructors; XML attributes will not work

这句话的意思是:自定义视图*不使用2 -或3-argument视图构造函数;XML属性将不会工作

这样一目了然,错误就迎刃而解了

在DrawView中添加2个构造函数即可

 public DrawView(Context context, AttributeSet attrs) {

        super(context, attrs );
    }

    public DrawView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle );
    }

 

OK,问题解决!

 

posted @ 2016-12-26 14:20  学永不止步  阅读(1620)  评论(0)    收藏  举报