2

我正在开发一款适用于 Android 的记忆游戏,但遇到了问题。当用户点击第二张图像时 - 如果图像不同,我希望第二张图像显示 1、2 秒。

我试过的是睡1-2秒。激活第二张图片后的 UI 线程 - 但这似乎不起作用 - 第二张图片似乎没有显示!(仅显示第一张图片)

这是我的代码:

public void whenTapedImage(View v, int position)
{
    i++;
    ImageView imgV=(ImageView)v;
    if(i%2!=0)
    {
        firstClick=position;
        imgV.setImageResource(im.images.get(firstClick));           
    }
    else
    {   
        secondClick=position;
        imgV.setImageResource(im.images.get(secondClick));                      
        try {
            Thread.currentThread().sleep(1000);
            if(!(im.images.get(firstClick).equals(im.images.get(secondClick))))
            {
                Toast.makeText(easyGame.this, "Try Again!", Toast.LENGTH_SHORT).show();
                im.notifyDataSetChanged();
                gridview.setAdapter(im);
                gridview.invalidate();
                aux=player1Turn;
                player1Turn=player2Turn;
                player2Turn=aux;
            }
            else{
                done=done+2;
                ImageAdapter.keepVisibleViews.add(firstClick);
                ImageAdapter.keepVisibleViews.add(secondClick);
                if(player1Turn==true)
                {
                    player1Score++;
                    String score=Integer.toString(player1Score);
                    score1.setText(score);
                }
                if(player2Turn==true)
                {
                    player2Score++;
                    String score=Integer.toString(player2Score);
                    score2.setText(score);
                }
            }   
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }           
}

我究竟做错了什么?

4

2 回答 2

7

您不能休眠 UI 线程,因为这会阻止 android 将任何其他事件传递到您的 Activity 的 UI。

相反,做一些事情,例如使用计时器,并让计时器的方法使用在 ui 线程上运行的工具来进行所需的延迟更改。

为了稳健性,您可能需要实现一个状态机(正式或实际)以跟踪应该发生的事情 - 如果按下另一个按钮,您需要决定是否应该中止或强制执行当前延迟,并让状态机适当地对待它。

于 2012-06-12T18:34:45.053 回答
5

这类似于在 android 应用程序中等待

尝试按照那里发布的解决方案并使用Timer Class

于 2012-06-12T18:39:54.300 回答