1

I'm working on a Tetris-app and I have a Thread.sleep command to animate the falling of the tetriminos. But that creates a conflict with the UI. So I tried runOnUiThread() like this:

while (gameover == false) { 
    tetriminoSettled = false;
    try {
        Thread.sleep(1000 - (counter * 3));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Random ran = new Random();
            int x = ran.nextInt(7) + 1;
            addTetrimino(createTetrimino(x)); //the UI operation
            gridView.invalidate();
        }
    });

But the UI gets only updated after the game ends. Do you think AsyncTask is a good approach? Please try to keep in mind that I later need additional UI-Threads for shifting the tetriminos left and right and so on. Thanks!

2 Answers2

1

Judging from the code you posted, it looks like you are using a gridview for a game. It is possible but not worth the effort. Just use a SurfaceView as shown in this short tutorial. You'll have an onDraw callback in which you can update whatever you like every drawing cycle. Have fun, coding games is really hard :).

Cottontree
  • 94
  • 6
  • You caught me!*g* I thought it might be applicable for Tetris, but I was also sure that there are better ways out there to do it. I will look into the tutorial. Thanks – user1734984 Feb 24 '17 at 08:10
  • It can be applicable for Tetris, but you dont want to handle multiple threads in a game on your own. its just horror. – Cottontree Feb 24 '17 at 10:44
0

Try gridView.postInvalidate();

Hamidreza
  • 1,360
  • 11
  • 18