Agar tidak terjadi multiple click atau pemanggilan event click berkali-kali, maka perlu sebuah trik untuk mencegahnya.
Sebenarnya ada banyak cara untuk mengakali trik ini, namun yg saya gunakan disini adalah trik yang sangat sederhana yaitu menghentikan aksi pada method onClick() dalam selang waktu tertentu yg kita tentukan.
1. Buat sebuah abstract class yang mengimplements View.OnClickListener.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.hangga.research; import android.os.SystemClock; import android.view.View; import java.util.Map; import java.util.WeakHashMap; /** * Created by hangga on 18/02/16. */ public abstract class SingleClickListener implements View.OnClickListener { private final long minimumInterval; private Map<View, Long> lastClickMap; /** * Implement this in your subclass instead of onClick * @param v The view that was clicked */ public abstract void onSingleClick(View v); /** * The one and only constructor * @param minimumIntervalMsec The minimum allowed time between clicks - any click sooner than this after a previous click will be rejected */ public SingleClickListener(long minimumIntervalMsec) { this.minimumInterval = minimumIntervalMsec; this.lastClickMap = new WeakHashMap<View, Long>(); } public SingleClickListener() { this.minimumInterval = 2000; // 2 second this.lastClickMap = new WeakHashMap<View, Long>(); } @Override public void onClick(View clickedView) { Long previousClickTimestamp = lastClickMap.get(clickedView); long currentTimestamp = SystemClock.uptimeMillis(); lastClickMap.put(clickedView, currentTimestamp); if(previousClickTimestamp == null || (currentTimestamp - previousClickTimestamp.longValue() > minimumInterval)) { onSingleClick(clickedView); } } } |
2. How to use
0 1 2 3 4 5 6 7 8 |
txtEdan.setOnClickListener(new SingleClickListener() { @Override public void onSingleClick(View v) { Intent intent; intent = new Intent(getContext(), UserActivity.class); intent.putExtra("userName",groupName); intent.putExtra("userId", groupId); getContext().startActivity(intent); } |