雙擊:
先來看簡單的實現方式
private void initView() {
// 找到按鈕控件
btn = (Button) findViewById(R.id.button);
// 設置點擊事件監聽
btn.setOnClickListener(this);
}
//初始化第一次點擊的標記
long fristTime=0;
@Override
public void onClick(View v) {
if (fristTime == 0) {
fristTime = System.currentTimeMillis();//獲取第一次點擊的時間
new Thread() {
public void run() {
try {
Thread.sleep(500);
fristTime = 0;//爲雙擊做準備
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
} else {
long secondTime = System.currentTimeMillis();//獲取第二次點擊的時間
if (secondTime - fristTime < 500) {
System.out.println("我被雙擊了。。。");
fristTime = 0;//爲下次雙擊做準備
}
}
}
三擊:
同理,用上面這種方式也能實現三擊,只是麻煩了些。參考Google,安卓手機中在查看安卓系統版本的地方,三擊或者多擊會出現彩蛋,可以借鑑其源碼進行實現。
//利用數組來存儲時間
long[] mHits = new long[3];
@Override
public void onClick(View v) {
// arraycopy 拷貝數組
/* 參數解讀如下:
* src the source array to copy the content. 拷貝哪個數組
* srcPos the starting index of the content in src. 從原數組中的哪裏開始拷貝
* dst the destination array to copy the data into. 拷貝到哪個數組
* dstPos the starting index for the copied content in dst. 從目標數組的那個位置開始去寫
* length the number of elements to be copied. 拷貝的長度
*/
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
//獲取離開機的時間
mHits[mHits.length - 1] = SystemClock.uptimeMillis();
//單擊時間的間隔,以500毫秒爲臨界值
if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
System.out.println("我被三擊了。。。");
//一個三擊(雙擊或多擊事件完成),
//把數組置爲空並重寫初始化,爲下一次三擊(雙擊或多擊)做準備
mHits = null;
mHits = new long[3];
}
}
多擊:
我們只需把數組的長度進行相應的更改,例如,把 new long[3]中的3改爲2 或者其它數字 ,即可實現雙擊或多擊的功能。