Thread.Sleep()Android UI

Ali*_*lin 2 user-interface multithreading android

我正在研究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();
        }   
    }           
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Chr*_*ton 7

你不能睡觉UI线程,因为这会阻止android向你的活动的UI提供任何其他事件.

相反,做一些事情,比如使用计时器并让计时器的方法使用ui线程工具上的run来进行所需的推迟更改.

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


The*_*ngK 5

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

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