在android系统中。google提供了一个click事件。只负责相应单次点击。
如果想实现双机或者多击事件的话就需要借鉴下google原生应用的源码了。
在android中,三次点击android的版本图标会出现一个相应版本的logo。
来看看google工程师是怎么写的。
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference.getKey().equals(KEY_FIRMWARE_VERSION)) {
System.arraycopy(mHits, 1, mHits, 0, mHits.length-1);
mHits[mHits.length-1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis()-500)) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("android",
com.android.internal.app.PlatLogoActivity.class.getName());
try {
startActivity(intent);
} catch (Exception e) {
Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
}
}
} else if (preference.getKey().equals(KEY_BUILD_NUMBER)) {
// Don't enable developer options for secondary users.
if (UserHandle.myUserId() != UserHandle.USER_OWNER) return true;
if (mDevHitCountdown > 0) {
if (mDevHitCountdown == 1) {
if (super.ensurePinRestrictedPreference(preference)) {
return true;
}
}
mDevHitCountdown--;
if (mDevHitCountdown == 0) {
getActivity().getSharedPreferences(DevelopmentSettings.PREF_FILE,
Context.MODE_PRIVATE).edit().putBoolean(
DevelopmentSettings.PREF_SHOW, true).apply();
if (mDevHitToast != null) {
mDevHitToast.cancel();
}
mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_on,
Toast.LENGTH_LONG);
mDevHitToast.show();
} else if (mDevHitCountdown > 0
&& mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER-2)) {
if (mDevHitToast != null) {
mDevHitToast.cancel();
}
mDevHitToast = Toast.makeText(getActivity(), getResources().getQuantityString(
R.plurals.show_dev_countdown, mDevHitCountdown, mDevHitCountdown),
Toast.LENGTH_SHORT);
mDevHitToast.show();
}
} else if (mDevHitCountdown < 0) {
if (mDevHitToast != null) {
mDevHitToast.cancel();
}
mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_already,
Toast.LENGTH_LONG);
mDevHitToast.show();
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
设置设置应用中实现三击的源码。简单的提取一下,可以得到n击事件的源码
private void doubleClick() {
final long[] mHits = new long[2];
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
mHits[mHits.length - 1] = SystemClock.uptimeMillis();
if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
// 双击事件
}
}
});
}
原理分析:
将每次的点击事件依次存放到一个定长的容器中。再对比第一次跟最后一次之间的时间差,如果满足一定的条件的。就认为是多击事件。