Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

July 07, 2021

Prevent or avoid Multiple clicks in Android app [Kotlin]

July 07, 2021 Posted by Piash , No comments

 Step 1 : Create class with name SafeClickListener.kt

 class SafeClickListener(  
 private var defaultInterval: Int = 1000,  
 private val onSafeCLick: (View) -> Unit  
  ) : View.OnClickListener {  
 private var lastTimeClicked: Long = 0  
 override fun onClick(v: View) {  
   if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) {  
     return  
   }  
   lastTimeClicked = SystemClock.elapsedRealtime()  
   onSafeCLick(v)  
    }   
  }  

 Step 2 : Add extension function to make it works with any view, this will create a new SafeClickListener and delegate the work to it.

   fun View.setSafeOnClickListener(onSafeClick: (View) -> Unit) {  
   val safeClickListener = SafeClickListener {  
     onSafeClick(it)  
    }  
   setOnClickListener(safeClickListener)  
  }  

 Step 3 : Now it is very easy to use it. Just replace button1.setonclicklistner with setSafeOnClickListener.

 settingsButton.setSafeOnClickListener {  
   showSettingsScreen()  
 }  

0 comments:

Post a Comment