Android实现掷骰子效果实现掷骰子效果
主要为大家详细介绍了Android实现掷骰子效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣
的小伙伴们可以参考一下
本文实例为大家分享了Android实现掷骰子效果的具体代码,供大家参考,具体内容如下
利用handler接受子线程的消息完成骰子点数的不断更替
演示演示
START:开始游戏
STOP:停止游戏
RECOVER:重置色子到初始状态
代码代码
package com.example.homeworkten;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ImageView imageView1,imageView2,imageView3;
private Button button1,button2,button3;
private ImageView[] imageViews;
private Handler handler;
//子线程
private Thread thread;
//记录每个色子的点数
private int number[];
//色子的总点数
private int count;
//volatile修饰符用来保证其它线程读取的总是该变量的最新的值
public volatile boolean isStop = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = new int[3];
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
imageView3 = findViewById(R.id.imageView3);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
imageViews = new ImageView[]{imageView1,imageView2,imageView3};
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//判断线程是否存在
if (thread != null&&isStop == true){
isStop = false;
}
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
for(int i = 0;i < 3;i++) {
switch (number[i]) {
case 1:
imageViews[i].setImageResource(R.drawable.t1);
break;
case 2:
imageViews[i].setImageResource(R.drawable.t2);
break;
case 3: