当我运行应用程序并触摸位图有时应用程序崩溃
这是错误:
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.example.Game.GFXSurface$GameSurface.run(GFXSurface.java:135)
at java.lang.Thread.run(Thread.java:864)
它崩溃的代码,如果我删除balls.remove
和balls.add
一切正常,但它不会生成新的球,并且在运行方法中,一切都可以正常使用remove
和add
:
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
GameSurface gamesurface = new GameSurface(this);
x = event.getX();
y = event.getY();
Bitmap ball = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
for (int i = 0; i < 4; i++)
if (ourSurfaceView.MouseOnDot(ball) && x >= ballX[i]
&& x <= ballX[i] + 72) {
balls.remove(i);
balls.add(i, gamesurface.RandomBall());
ChangingY[i] = 0;
if (speed <= 7)
speed += 0.1;
}
return false;
}
这里的方法是balls.get
@Override
public void run() {
for (int j = 0; j < 4; j++) {
balls.add(j, RandomBall());
}
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(02, 02, 150);
for (int i = 0; i < 4; i++) {
ballX[i] = i * 155;
canvas.drawBitmap(balls.get(i), ballX[i], ChangingY[i],
null);
if (ChangingY[i] <= canvas.getHeight()) {
ChangingY[i] += 1 * speed;
} else if (ChangingY[i] > canvas.getHeight()) {
ChangingY[i] = 0;
if (speed <= 5)
speed += 0.25;
balls.remove(i);
balls.add(i, RandomBall());
}
}
// }
ourHolder.unlockCanvasAndPost(canvas);
}
}
答案 0 :(得分:2)
错误表示用于访问ArrayList的索引大于ArrayList大小。
尝试代替for(int i = 0; i&lt; 4; i ++)用于(int i = 0; i&lt; balls.size(); i ++)
或者当你使用balls.remove(i)先检查我是否&lt; balls.size