package com.itheima52.doubleclick; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
/**
* 模拟双击事件
*/
public class MainActivity extends Activity { private long firstClickTime; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
if (firstClickTime > 0) {// 发现之前点击过一次
if (System.currentTimeMillis() - firstClickTime < 500) {// 判断两次点击是否小于500毫秒
Toast.makeText(this, "双击啦!", Toast.LENGTH_SHORT).show();
firstClickTime = 0;//重置时间, 重新开始
return;
}
}
firstClickTime = System.currentTimeMillis();
}
}
n次点击:
package com.itheima52.moreclick; import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
long[] mHits = new long[3];// 数组长度表示要点击的次数,3表示3次点击,4表示4次点击。数组初始化都为0 public void onClick(View view) {//源码
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);//原数组,原数组拷贝起始点,目标数组,目标数组拷贝起始点。
mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后开始计算的时间,每次放在最后一个,
if ((mHits[mHits.length - 1] - mHits[0]) <= 500) {//最后一个和第一个相差500毫秒
Toast.makeText(this, "是男人!!!", Toast.LENGTH_SHORT).show();
}
}
}