首先:我们是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;
}
使用如下所示的touchView类:
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);
}
}
不幸的是,它不起作用,我们完全失去了如何让它发挥作用。有人可以帮助我们吗?
答案 0 :(得分:0)
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;
}
}