Skip to content

Instantly share code, notes, and snippets.

@msdx msdx/TypeExtensions.kt
Last active Oct 17, 2018

Embed
What would you like to do?
Kotlin extensions
fun Date.toCalendar(): Calendar = Calendar.getInstance().apply { this.time = this@toCalendar }
fun Calendar.addDayOfMonth(amount: Int): Calendar {
this.add(Calendar.DAY_OF_MONTH, amount)
return this
}
fun Calendar.formatTo(formatter: SimpleDateFormat): String {
return formatter.format(this.timeInMillis)
}
val Calendar.year: Int get() = this.get(Calendar.YEAR)
var Calendar.month: Int
get() = this.get(Calendar.MONTH)
set(value) = this.set(Calendar.MONTH, value)
val Calendar.dayOfMonth: Int get() = this.get(Calendar.DAY_OF_MONTH)
inline fun <T> Iterable<T>.sumByFloat(selector: (T) -> Float): Float {
var sum = 0f
for (element in this) {
sum += selector(element)
}
return sum
}
fun String.toIntOrZero(): Int = if (this.isEmpty()) 0 else this.toInt()
fun String.toFloatOrZero(): Float = if (this.isEmpty()) 0f else this.toFloat()
val TextView.textString: String get() = this.text.toString()
fun Button.dependsOnNotEmpty(vararg editTexts: EditText) {
val textWatcher = object : SimpleTextWatcher() {
override fun afterTextChanged(s: Editable?) {
for (edit in editTexts) {
if (edit.text.isEmpty()) {
this@dependsOnNotEmpty.isEnabled = false
return
}
}
this@dependsOnNotEmpty.isEnabled = true
}
}
editTexts.forEach { it.addTextChangedListener(textWatcher) }
}
fun Button.dependsOn(vararg editTexts: EditText, isEnabled: (() -> Boolean)){
val textWatcher = object : SimpleTextWatcher() {
override fun afterTextChanged(s: Editable?) {
this@dependsOn.isEnabled = isEnabled()
}
}
editTexts.forEach { it.addTextChangedListener(textWatcher) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.