我正在为 Android 开发一个 opengl 游戏。当用户松开游戏时应该返回主菜单,但是这个调用是从 OpenGL ES 线程到 UI 线程进行的,存在一些麻烦。我发现这篇文章使用 queueEvent() 在渲染器和另一个类之间传递变量,并尝试在以下代码中添加 Handler 类:
public class GameActivity extends Activity {
private GLSurfaceView gameView;
private int menuViewID;
private Handler gameOverHandler;
public GameActivity () {
super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameOverHandler = new Handler() {
public void handleMessage (Message msg){
handleGameOver();
}
};
gameView = new GameView(this, gameOverHandler);
menuViewID = R.layout.main;
setContentView(menuViewID);
}
/** Called when the user selects the Send button */
public void startGame(View view) {
setContentView(gameView);
gameView.setVisibility(View.VISIBLE);
}
private void handleGameOver() {
/**
* TODO: switch back to main menu
*/
// setContentView(menuViewID); // after this gameView freezes
// gameView.setVisibility(View.GONE); // after this application throw an error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
}
}
然后在 OpenGL ES 代码中
gameOverHandler.dispatchMessage(Message.obtain(gameOverHandler));
但我仍然遇到冻结或运行时异常(请参阅上面代码中的注释行)。我在这里错过了什么或做错了什么?
顺便说一句,如何获取在 XML 中定义的 View 实例的引用(参见menuViewID
上面的代码),或者该findViewById
方法为什么返回NULL
?