按鍵防止連續點擊是任何一個項目都要考慮的功能.下面咱們將介紹幾種防止按鍵連續點擊的方法網絡
/** *@content:按鍵延時工具類,用於防止按鍵連點 *@time:2019-5-19 *@build: */ public class ButtonDelayUtil { private static final int MIN_CLICK_DELAY_TIME = 1000; private static long lastClickTime; public static boolean isFastClick(){ boolean flag = false; long curClickTime = System.currentTimeMillis(); if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) { flag = true; } lastClickTime = curClickTime; return flag; } }
mAdapter.setItemClickListener(new PTempEventListAdapter.OnItemClickListener() { @Override public void onItemClick(PTempEventListBase.TempEventData tempEventData) { if (ButtonDelayUtil.isFastClick()){ Intent intent = new Intent(PTempEventListActivity.this, PTempEventDetailActivity.class); intent.putExtra(PTempEventDetailActivity.APPLY_ID_KEY, tempEventData.getApplyId()); startActivity(intent); } } });
很簡單,可是使用的時候也很麻煩.也會讓代碼很是不簡潔,能夠做爲一種補充辦法.ide
public abstract class OnForbidClickListener implements View.OnClickListener { private static final long DELAYED_TIME = 1000; private long lastTime = 0; public abstract void forbidClick(View view); @Override public void onClick(View v) { if (System.currentTimeMillis()-lastTime > DELAYED_TIME){ lastTime = System.currentTimeMillis(); forbidClick(v); } } }
mFaceInfoText.setOnClickListener(new OnForbidClickListener() { @Override public void forbidClick(View view) { Intent startFaceHome = new Intent(PParentInfoActivity.this, FaceHomeActivity.class); startFaceHome.putExtra(FaceHomeActivity.FACE_USER_ID_KEY, mParentId); startFaceHome.putExtra(FaceHomeActivity.FACE_IDENTITY_TYPE_KEY, 2); startFaceHome.putExtra(FaceHomeActivity.FACE_SCHOOL_ID_KEY, PSPDataSession.I().getCurrentChildData().getSchoolId()); startActivity(startFaceHome); } });
其實跟上面的工具類是相似的,只不過將實現方式放入了重寫的點擊接口類裏,也麻煩,可是至少會代碼簡潔一些工具
其實上面的2個方式依然有可能被連點,好比點擊後發送的是網絡請求,請求完成後若是會finish Activity 就算你加了等待對話框,依然會有在等待對話框關閉 activity準備關閉的時候一直點擊提交按鈕的狀況下觸發第二次的網絡請求.post
因此下面方式就比較麻煩了,可是是能最好防止功能被連點的方式.因此通常是使用在網絡請求上.ui
private boolean mPostAddApiing = false;
在請求接口的時候this
mSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(mEditPhoneNumber.getText()) || mEditPhoneNumber.getText().toString().length() < 11) { Toast.makeText(PParentAddActivity.this, "請輸入正確的電話號碼", Toast.LENGTH_SHORT).show(); return; } if (mEditVerificationCode.getText().toString().length() < 6) { Toast.makeText(PParentAddActivity.this, "請輸入正確的驗證碼", Toast.LENGTH_SHORT).show(); return; } if (!mPostAddApiing){ mPostAddApiing = true; postAddApi(); } } });
而後在接口回調裏若是是成功就不在處理mPostAddApiing 直接關閉finish activity,若是是activity不用關閉/提交失敗/網絡異常/用戶主動取消請求的狀況下,都要操做 mPostAddApiing = false, 讓按鍵恢復能夠點擊;spa
固然也能夠使用下面的方式同樣能夠達到效果,只要在對應想要開關的地方處理點擊,可是這個邏輯上就比較隱式了code
mSubmit.setClickable(false);