在计时器上更改图像并开始onClick

时间:2014-04-12 16:04:24

标签: java android

我正在用骰子制作这个应用程序。当用户触摸骰子的图像时,图像变为随机的其他骰子。为了使它看起来像用户'投掷'骰子,图像在停止在随机图像之前改变几次(6)。以下是我的代码示例:

public class MainActivity extends Activity {

int changes = 0;
int n;
int[] heads = {R.drawable.dice1,R.drawable.dice2,R.drawable.dice3,
        R.drawable.dice4,R.drawable.dice5,R.drawable.dice6};
Handler handler;
boolean Running = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    handler = new Handler();
    Runnable runnable = new Runnable(){

        @Override
        public void run() {

            while(Running){
                try{
                    Thread.sleep(200);}
                catch(InterruptedException e){
                    e.printStackTrace();
                }
                handler.post(new Runnable(){

                    public void run(){
                        Random rdm = new Random();
                        n = rdm.nextInt(6);

                         ImageView image = (ImageView) findViewById(R.id.imageDice1);
                         image.setImageResource(heads[n]);
                         changes++;

                         if(changes == 6){
                        Running = false;
                        changes == 0;
                        }
                    }


                });
            }

   };

};

  new Thread(runnable).start();

    }

   public void imageClick(View v) {  
    Running = true;   //this has no effect.

 }

}

骰子改变6次后(变化= = 6),它停止。这可以工作,但问题是单击图像时它不会运行(imageClick)。其他命令在imageClick中有效,但'Running = true'不行。我应该在那里写什么才能让用户“掷出”骰子?

1 个答案:

答案 0 :(得分:0)

将该线程放入onclick

   public void imageClick(View v) {  
    Running = true;
    new Thread(runnable).start(); // start the thread when image is clicked
 }

也将runnable声明为成员变量。

Runnable runnable;

和onCreate

runnable = new Runnable(){.......