Android OnTouch 给出一个错误



首先:我们是Android开发的新手,我们有一个练习,我们不明白我们需要做什么。

我们需要将OnTouchListener添加到touchView,根据课程幻灯片,这可以如下所述完成,但它不起作用:

public class MainActivity extends AppCompatActivity{
TouchView touchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    this.setContentView(ll);
    float x = 500;
    float y = 500;
    float size = 1000;
    touchView = new TouchView(x,y,size,this);
    touchView.setOnTouchListener(this);
    ll.addView(touchView);
}
public boolean onTouch(View view, MotionEvent motionEvent){
    float x = motionEvent.getX();
    float y = motionEvent.getY();
    return  true;
}

使用如下所示的触摸视图类:

public class TouchView extends View {
public float x,y,size;
Paint paint = new Paint();
public TouchView(float xcor, float ycor, float sizenum, Context context) {
    super(context);
    x = xcor;
    y = ycor;
    size = sizenum;
    paint.setAntiAlias(true);
}

@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);
    paint.setColor(Color.BLUE);
    canvas.drawCircle(x, y, size, paint);
}
public TouchView(Context context, AttributeSet attributeSet){
    super(context, attributeSet);
}
}

不幸的是,它不起作用,我们对如何使其工作完全不知所措。有人可以帮助我们吗?

public class MainActivity extends AppCompatActivity implement OnTouchListener {
   TouchView touchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        this.setContentView(ll);
        float x = 500;
        float y = 500;
        float size = 1000;
        touchView = new TouchView(x,y,size,this);
        touchView.setOnTouchListener(this);
        ll.addView(touchView);
    }
    public boolean onTouch(View view, MotionEvent motionEvent){
        float x = motionEvent.getX();
        float y = motionEvent.getY();
        return  true;
    }
}

相关内容

最新更新