通过自定义的CountingHandler实现打地鼠小游戏,单击地鼠表示打中,并记录打中地鼠总数(地鼠一共出现10次);
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
View.OnTouchListener {
public static final int CODE = 10001;
public static final int DELAY_TIME = 500;
private TextView resultText;
private Button beginBtn;
private ImageView susliksImg;
//地鼠位置的坐标
public int[][] mPositions = new int[][]{
{123,323},{434,234},
{231,242},{264,111},
{300,400},{329,111},
{231,231},{452,427}
};
private int MAX_COUNT = 10;
private int totalCount = 0;
private int hitCount = 0;
CountingHandler handler = new CountingHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
resultText = (TextView) findViewById(R.id.result_txt);
beginBtn = (Button) findViewById(R.id.star_button);
susliksImg = (ImageView) findViewById(R.id.susliks_img);
susliksImg.setOnTouchListener(this);
beginBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
start();
}
/**
* 发送message
*/
private void start() {
beginBtn.setText("进行中...");
beginBtn.setEnabled(false);
resultText.setText("游戏开始了!");
next(0);
}
/**
* delayTime为传入的延迟时间
*/
private void next(int delayTime) {
int i = new Random().nextInt(mPositions.length);
Message message = Message.obtain();
message.what = CODE;
message.arg1 = i;
handler.sendMessageDelayed(message, delayTime);
totalCount ++;
}
//打中地鼠响应
@Override
public boolean onTouch(View v, MotionEvent event) {
hitCount ++;
resultText.setText("您打中了" + hitCount + "只地鼠,一共10只!");
susliksImg.setVisibility(View.GONE);
return false;
}
public static class CountingHandler extends Handler{
public final WeakReference<MainActivity> mWeakReference;
public CountingHandler(MainActivity activity) {
this.mWeakReference = new WeakReference<>(activity);
}
//处理消息,设置地鼠的位置等。
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//得到MainActivity弱引用
MainActivity activity = mWeakReference.get();
switch (msg.what){
case CODE:
//判断是否打完地鼠
if(activity.totalCount > activity.MAX_COUNT){
activity.clear();
Toast.makeText(activity, "地鼠打完了!!", Toast.LENGTH_SHORT)
.show();
return ;
}
int i = msg.arg1;
activity.susliksImg.setX(activity.mPositions[i][0]);
activity.susliksImg.setY(activity.mPositions[i][1]);
activity.susliksImg.setVisibility(View.VISIBLE);
//随机的时间传入为地鼠出现的延迟时间 (0 + 500) =< randomTime < (500 + 500)
int randomTime = new Random().nextInt(DELAY_TIME) + DELAY_TIME;
activity.next(randomTime);
}
}
}
//清除数据
private void clear() {
totalCount = 0;
beginBtn.setText(R.string.begin_game);
beginBtn.setEnabled(true);
hitCount = 0;
susliksImg.setVisibility(View.GONE);
}
}
通过handleMessage方法再次调用弱引用的MainAcitiviity的next方法send message就可以将地鼠出现及相应操作循环起来。同时静态类和弱引用也防止了内存的泄漏。
运行的结果如下图: