Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
EmmanuelGuther / ElvisOperatorExample.kt
Created August 22, 2019 11:41
Kotlin elvis operator example
Elvis Operator
When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x":
val l: Int = if (b != null) b.length else -1
Along with the complete if-expression, this can be expressed with the Elvis operator, written ?::
val l = b?.length ?: -1
If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null.
Note that, since throw and return are expressions in Kotlin, they can also be used on the right hand side of the elvis operator. This can be very handy, for example, for checking function arguments:
@EmmanuelGuther
EmmanuelGuther / TextView.showCountIncrementAnimation.kt
Created August 1, 2019 10:29
A kotlin extension to set numbers in textview one by one
fun TextView.showCountIncrementAnimation(from: Int? = 0, to: Int?) {
var duration: Long? = null
val animator = ValueAnimator()
animator.setObjectValues(from, to)// here you set the range, from 0 to "count" value
animator.addUpdateListener { animation -> this.text = animation.animatedValue.toString() }
duration = when (to) {
in 0..4 -> 200
in 5..10 -> 1000
in 11..50 -> 3000
else -> 2000
fun TextView.afterTextChangedDelayed(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
var timer: CountDownTimer? = null
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
@EmmanuelGuther
EmmanuelGuther / GenerateRandomLocationInsideRadius.kt
Created July 18, 2019 09:53
Kotlin generate random location inside radius
fun generateRandomLocationInsideRadius(x0: Double, y0: Double, radius: Int): LatLng {
val random = Random()
// Convert radius from meters to degrees
val radiusInDegrees = (radius / 111000f).toDouble()
val u = random.nextDouble()
val v = random.nextDouble()
val w = radiusInDegrees * sqrt(u)
val t = 2.0 * Math.PI * v
val x = w * cos(t)
val y = w * sin(t)
@EmmanuelGuther
EmmanuelGuther / RandomString.kt
Created July 18, 2019 09:48
Kotlin function random string
/** USAGE -> ('a'..'z').randomString(6) */
fun ClosedRange<Char>.randomString(lenght: Int) =
(1..lenght)
.map { (Random().nextInt(endInclusive.toInt() - start.toInt()) + start.toInt()).toChar() }
.joinToString("")
@EmmanuelGuther
EmmanuelGuther / build.gradle
Created July 16, 2019 07:55
Function to increase the versionCode automatically
private Object increaseVersionCode() {
Properties versionProps = new Properties()
def versionPropsFile = file('version.properties')
if (versionPropsFile.exists())
versionProps.load(new FileInputStream(versionPropsFile))
def code = (versionProps['VERSION_CODE'] ?: "410").toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
return code
}
val fiveMinutes = (1000 * 60 * 5).toLong() //5m in milliseconds
@EmmanuelGuther
EmmanuelGuther / ExtensionFunctionChecktimeOldThan.kt
Created May 8, 2019 17:55
Extension function to check if timestamp value is before X days
fun Long.checkTimeIsOldThan(days: Int): Boolean {
val daysInMillis = TimeUnit.DAYS.toMillis(days.toLong())
val currentTime = Date().time
val previousTime = this
val differ = currentTime - previousTime
return !(differ < daysInMillis && differ > -daysInMillis)
}
@EmmanuelGuther
EmmanuelGuther / AndroidScreenSizesReferences.txt
Created April 25, 2019 10:23
Android screen sizes references
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Galaxy Y 320 x 240 ldpi 0.75 120 427 x 320 4:3 1.3333 427 x 320
? 400 x 240 ldpi 0.75 120 533 x 320 5:3 1.6667 533 x 320
? 432 x 240 ldpi 0.75 120 576 x 320 9:5 1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi 1 160 480 x 320 3:2 1.5000
@EmmanuelGuther
EmmanuelGuther / functionAsParameter.kt
Created April 4, 2019 18:10
Kotlin pass a function as parameter and execute
internal fun handleChatMessages(messages: List<MessageModel>?) {
hideProgress()
adapter.collection = messages.orEmpty()
animate { runLayoutAnimation() }
}
private fun animate(function: () -> Unit) {
when {
firstTimeCreated -> function.invoke()
}