Skip to content

Instantly share code, notes, and snippets.

@nikartx
Created February 25, 2022 14:05
Show Gist options
  • Save nikartx/c00f8a96f4efb0362b7ce661d5e169bc to your computer and use it in GitHub Desktop.
Save nikartx/c00f8a96f4efb0362b7ce661d5e169bc to your computer and use it in GitHub Desktop.
Loading [MaterialButton]. Support showing loading spinner on the button
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.swiperefreshlayout.widget.CircularProgressDrawable
import com.google.android.material.button.MaterialButton
/**
* Loading [MaterialButton]. Showing loading spinner on the button
*
* @author Ivan V on 24.02.2022
*/
class LoadingMaterialButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : MaterialButton(context, attrs, defStyleAttr) {
companion object {
private const val EMPTY_TEXT = ""
}
private var btnText = EMPTY_TEXT
private val progressDrawable by lazy {
CircularProgressDrawable(context).apply {
setStyle(CircularProgressDrawable.DEFAULT)
setColorSchemeColors(Color.WHITE)
}
}
private val callback = object : Drawable.Callback {
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
// Do nothing
}
override fun invalidateDrawable(who: Drawable) {
invalidate()
}
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
// Do nothing
}
}
fun startLoading() {
btnText = text.toString()
text = EMPTY_TEXT
enableButton(false)
progressDrawable.callback = callback
foreground = progressDrawable
progressDrawable.start()
}
fun stopLoading() {
text = btnText
enableButton(true)
if (progressDrawable.isRunning) {
progressDrawable.stop()
}
}
private fun enableButton(enabled: Boolean) {
isClickable = enabled
isFocusable = enabled
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stopLoading()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment