Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 更改计时器上的图像并启动onClick_Java_Android - Fatal编程技术网

Java 更改计时器上的图像并启动onClick

Java 更改计时器上的图像并启动onClick,java,android,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,

我正在用骰子制作这个应用程序。当用户触摸模具的图像时,图像会变成随机的其他模具。为了让它看起来像是用户“掷”骰子,图像会在随机图像停止之前更改几次(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”不起作用。为了让用户“扔”骰子,我应该在那里写些什么呢?

将该线程放在onclick中

   public void imageClick(View v) {  
    Running = true;
    new Thread(runnable).start(); // start the thread when image is clicked
 }
还将runnable声明为成员变量

Runnable runnable;
再创造

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

这会产生一个错误:“runnable无法解析为变量”。哦。您需要声明runnable as字段。。编辑答案