Skip to content

Instantly share code, notes, and snippets.

@Younes-Charfaoui
Created September 20, 2021 17:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Younes-Charfaoui/5b6db0d7891dd33400ad637f85843df9 to your computer and use it in GitHub Desktop.
Save Younes-Charfaoui/5b6db0d7891dd33400ad637f85843df9 to your computer and use it in GitHub Desktop.
package com.mxcs.kotlin
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.Patterns
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import java.security.MessageDigest
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
fun View.visible() {
visibility = View.VISIBLE
}
fun View.gone() {
visibility = View.GONE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun Context.showSmallLengthToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun Context.showLongLengthToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
fun Activity.hasPermission(permission: String): Boolean {
return ActivityCompat.checkSelfPermission(
this,
permission
) == PackageManager.PERMISSION_GRANTED
}
fun String.isValidEmail(): Boolean =
this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
fun String.isValidPassword() = this.isNotEmpty() && this.length > 8 && this.containsDigit()
fun Int.toDate(): Date = Date(this.toLong() * 1000L)
fun String.toDate(format: String): Date? {
val dateFormatter = SimpleDateFormat(format, Locale.US)
return try {
dateFormatter.parse(this)
} catch (e: ParseException) {
null
}
}
fun Date.toString(format: String): String {
val dateFormatter = SimpleDateFormat(format, Locale.US)
return dateFormatter.format(this)
}
fun String.containsDigit() = matches(Regex(".*[0-9].*"))
fun Context.vibrate(duration: Long) {
val vib = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vib.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
vib.vibrate(duration)
}
}
fun String.sha1(): String {
val bytes = MessageDigest.getInstance("SHA-1").digest(this.toByteArray())
return bytes.joinToString("") {
"%02x".format(it)
}
}
fun View.onThrottledClick(
throttleDelay: Long = 500L,
onClick: (View) -> Unit
) {
setOnClickListener {
onClick(this)
isClickable = false
postDelayed({ isClickable = true }, throttleDelay)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment