android / android-ktx

A set of Kotlin extensions for Android app development.
https://android.github.io/android-ktx/core-ktx/
7.47k stars 563 forks source link

Does AdapterView deserve attention? #470

Open fada21 opened 6 years ago

fada21 commented 6 years ago

I was thinking about adding some AdapterView extentions. Some listeners setting extentions first for those:

I'm using them for Spinners in my project atm. Should I prepare PR?

romainguy commented 6 years ago

What would the extensions do?

fada21 commented 6 years ago

I'll just post method signature here. Later today or tomorrow prepare PR to be more precise and kick off detailed discussion.

@Suppress("UNCHECKED_CAST")
inline fun <ITEM> AdapterView<*>.onItemClick(
    crossinline onItemClick: (item: ITEM) -> Unit
)
@Suppress("UNCHECKED_CAST")
inline fun <ITEM> AdapterView<*>.onItemLongClick(
    crossinline onItemLongClick: (item: ITEM) -> Boolean
)
inline fun AdapterView<*>.onItemSelected(
    crossinline onNothingSelected: () -> Unit = {},
    crossinline onItemSelected: (parent: AdapterView<*>?, view: View?, position: Int, id: Long) -> Unit
)
@Suppress("UNCHECKED_CAST")
inline fun <ITEM> AdapterView<*>.onItemSelected(
    crossinline onNothingSelected: () -> Unit = {},
    crossinline onItemSelected: (item: ITEM) -> Unit
)

Generally some sugar on the AdapterView setting click listeners ceremony.

sohailehmad commented 6 years ago

setOnItemSelectedListener can be shorten as

inline fun <T> AdapterView<*>.doOnItemSelected(crossinline block: (item:T) -> Unit) {
    onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
        }

        @Suppress("UNCHECKED_CAST")
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            block(selectedItem as T)
        }
    }
}

Then we can use this extension like this

adapterView.doOnItemSelected<T> {
    //here Type of it will be T
}
fada21 commented 6 years ago

Work in progres PR is ready https://github.com/android/android-ktx/pull/484. I need to finish some tests but most importantly I'm waiting for feedback on implementation.

fada21 commented 6 years ago

@sohailehmad please note that with default argument for onNothingSelected you still can use method without specifying both arguments and can invoke it like that:

adapterView.onItemSelected<ITEM> { /* action */ }

I'd agree that onNothingSelected is rarely used but getting rid of of it completely as in your implementation proposition might not be the best options. Especially that we can have concise and general method that handle both arguments.

fada21 commented 6 years ago

PR updated and ready for review.