Skip to content

Instantly share code, notes, and snippets.

@msdx
Last active October 17, 2018 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msdx/b43bc33cbeeebeef16db0bbb72fc3218 to your computer and use it in GitHub Desktop.
Save msdx/b43bc33cbeeebeef16db0bbb72fc3218 to your computer and use it in GitHub Desktop.
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