【发布时间】:2023-03-16 13:45:01
【问题描述】:
我知道有很多这样的问题,但没有一个答案对我有用!
编辑 1:我想编写一个“乒乓”游戏。一个方法应该每帧重新计算和重新绘制球。
基本上我正在寻找另一种方法来执行此操作(每 16 毫秒更新一次视图以使游戏运行):
Thread t = new Thread(){
while (true){
try{
Thread.sleep(16);
} catch (InterruptedException e) {
}
invalidate();
}
}
t.start(); //here the code crashes
我已经通过Handler、TimerTask (link) 和Runnable 列出了一些。
当我收到android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views 时,我最好的尝试是:
Timer timer = new Timer();
final GameView v = this;
final TimerTask task = new TimerTask() {
@Override
public void run() {
v.invalidate();
}
};
timer.schedule(task, 100, 200);
编辑 2:m0skit0 的最佳方法:
Timer timer = new Timer();
final GameView v = this;
final TimerTask task = new TimerTask() {
@Override
public void run() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (!pause)
v.update(); //my invalidate()-method
}
});
}
};
timer.schedule(task, 0, 16);
致所有有工作想法的人:提前谢谢!
【问题讨论】:
-
你为什么首先要
invalidate()View?为什么要每 16 毫秒执行一次?invalidate()是一个相对昂贵的电话,而且通常不需要。 -
您可以使用
Activity#runOnUiThread()拨打您的invalidate(),但您可能需要先回答CommonsWare 的评论。如果您正在制作游戏,请考虑使用Canvas。 -
@CommonsWare 我使用来自
View的onDraw(Canvas c)-方法,那么我应该使用什么而不是invalidate()来重绘? -
嗯,对于游戏,我会使用游戏开发框架或引擎,无论是 2D 还是 3D,而不是直接使用
View系统。 -
@m0skit0 thx 这看起来不再漂亮了,但它终于可以工作了。即使是生涩的......
标签: android multithreading frames