出于某种原因,我似乎无法理解这一点。我想做的是每3秒钟出现三个图像中的任何一个,但由于某种原因,它给了我一个随机图像,然后另一个突然出现并消失。总的来说,我希望它每3秒生成一个图像,但由于某种原因无法使其工作。下面是我的VGameView的代码:
public class VGameView extends View {
private Bitmap parrot;
private Bitmap moneyChest;
private Bitmap bomb;
Random randy;
int savedTime = 0;
long lastTime;
int rndImg;
private String score = "Score: ";
private int scoreCounter = 0;
private Paint scorePaint = new Paint();
public VGameView(Context context) {
super(context);
parrot = BitmapFactory.decodeResource(getResources(), R.drawable.parrot);
moneyChest = BitmapFactory.decodeResource(getResources(), R.drawable.moneychest);
bomb = BitmapFactory.decodeResource(getResources(), R.drawable.bomb);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(50);
}
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
break;
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
String.valueOf(scoreCounter);
canvas.drawText(score + scoreCounter, 10, 100, scorePaint);
long now = System.currentTimeMillis();
savedTime += now - lastTime;
lastTime = now;
if (savedTime > 3000) {
savedTime = 0;
Random randy = new Random();
rndImg = (int) (3 * Math.random()) + 1;
if (rndImg == 1) {
canvas.drawBitmap(parrot, 200, 500, null);
}
if (rndImg == 2) {
canvas.drawBitmap(moneyChest, 600, 200, null);
}
if (rndImg == 3) {
canvas.drawBitmap(bomb, 30, 30, null);
}
}
}
答案 0 :(得分:1)
onDraw()
,之后只有在需要重置视图时才会调用它。当您调用invalidate()
方法时会发生这种情况。
所以,我建议你在创建视图的Activity中创建一个线程或一个处理程序,然后每隔3秒重置一次视图。
在VGameView中:
@Override
protected void onDraw(Canvas canvas) {
String.valueOf(scoreCounter);
canvas.drawText(score + scoreCounter, 10, 100, scorePaint);
rndImg = (int) (3 * Math.random()) + 1;
if (rndImg == 1) {
canvas.drawBitmap(parrot, 200, 500, null);
}
if (rndImg == 2) {
canvas.drawBitmap(moneyChest, 600, 200, null);
}
if (rndImg == 3) {
canvas.drawBitmap(bomb, 30, 30, null);
}
}
public void reset(){
invalidate();
}
内部活动:
Handler mHandler = new Handler();
Runnable changeImage = new Runnable() {
@Override
public void run() {
mview.reset();
mHandler.postDelayed(changeImage, 3000);
}
};
mHandler.postDelayed(changeImage, 3000);
告诉我这是否有效..
答案 1 :(得分:0)
使用postdelayed实现处理程序
private Handler mHandler;
Runnable imageChecker = new Runnable() {
@Override
public void run() {
try {
//update your image here
} finally {
mHandler.postDelayed(imageChecker, 3000);
}
}
};
的onCreate
mHandler = new Handler();
imageChecker.run();