mapbox-maps-android
mapbox-maps-android copied to clipboard
[spike] Create Kotlin extensions for some interfaces in order to simplify usage
Idea is to create extension functions to simplify usage of callback interface for kotlin developers. Here is an example: Instead of full implementation of interface:
gesturesPlugin.addOnMoveListener(object: OnMoveListener{
override fun onMoveBegin(detector: MoveGestureDetector) {
TODO("Not yet implemented")
}
override fun onMove(detector: MoveGestureDetector): Boolean {
TODO("Not yet implemented")
}
override fun onMoveEnd(detector: MoveGestureDetector) {
TODO("Not yet implemented")
}
})
We will be able to short it to:
gesturesPlugin.doOnMoveBegin {
do something
}
This is how Google does it:
public inline fun TextView.doBeforeTextChanged(
crossinline action: (
text: CharSequence?,
start: Int,
count: Int,
after: Int
) -> Unit
): TextWatcher = addTextChangedListener(beforeTextChanged = action)
/**
* Add an action which will be invoked when the text is changing.
*
* @return the [TextWatcher] added to the TextView
*/
public inline fun TextView.doOnTextChanged(
crossinline action: (
text: CharSequence?,
start: Int,
before: Int,
count: Int
) -> Unit
): TextWatcher = addTextChangedListener(onTextChanged = action)
/**
* Add an action which will be invoked after the text changed.
*
* @return the [TextWatcher] added to the TextView
*/
public inline fun TextView.doAfterTextChanged(
crossinline action: (text: Editable?) -> Unit
): TextWatcher = addTextChangedListener(afterTextChanged = action)
/**
* Add a text changed listener to this TextView using the provided actions
*
* @return the [TextWatcher] added to the TextView
*/
public inline fun TextView.addTextChangedListener(
crossinline beforeTextChanged: (
text: CharSequence?,
start: Int,
count: Int,
after: Int
) -> Unit = { _, _, _, _ -> },
crossinline onTextChanged: (
text: CharSequence?,
start: Int,
before: Int,
count: Int
) -> Unit = { _, _, _, _ -> },
crossinline afterTextChanged: (text: Editable?) -> Unit = {}
): TextWatcher {
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
afterTextChanged.invoke(s)
}
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) {
beforeTextChanged.invoke(text, start, count, after)
}
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged.invoke(text, start, before, count)
}
}
addTextChangedListener(textWatcher)
return textWatcher
}
Todo: create a list of APIs that we want to improve.