我正在制作一个 Android 应用程序。目标是制作圆圈,当被触摸时会发生一些事情。更详细地说,这个应用程序将显示 2 种类型的圆圈,一种是红色的,一种是绿色的。圆圈的颜色存储在 lastColor 变量中。颜色的目的是当用户“触摸”红色或绿色圆圈时会发生一些事情。例如,如果触摸一个绿色圆圈,则会将一个点添加到该分数中,或者如果单击一个红色圆圈,则活动会发生变化,但是当任何一个圆圈被单击时,都不会发生任何事情。这是 onTouch 方法
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
Intent i = new Intent(v.getContext(), YouFailed.class);
v.getContext().startActivity(i);
} else {
addPoints++;
}
}else {
}
return true;
}
这部分代码是无法正常运行的东西。这是下面的整个课程。
public class DrawingView extends View {
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
private final Runnable updateCircle = new Runnable() {
@Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
invalidate();
handler.postDelayed(this, 1000);
}
};
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
if (random == null) {
randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
}
else {
randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
}
canvas.drawCircle(randomWidth, randomHeight + radius / 2f, radius, paint);
paint.setColor(Color.BLACK);
paint.setTextSize(150);
canvas.drawText("Score: " + addPoints, 120, 300, paint);
}
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if (isInsideCircle(x, y) == true) {
//Do your things here
if (redColor == lastColor) {
Intent i = new Intent(v.getContext(), YouFailed.class);
v.getContext().startActivity(i);
}
else {
addPoints++;
}
}
else {
}
return true;
}
public boolean isInsideCircle(int x, int y) {
if ((((x - randomWidth) * (x - randomWidth)) + ((y - randomHeight) * (y - randomHeight))) < ((radius) * (radius)))
return true;
return false;
}
}