android-ktx icon indicating copy to clipboard operation
android-ktx copied to clipboard

Does AdapterView deserve attention?

Open fada21 opened this issue 7 years ago • 6 comments

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

  • setOnItemClickListener
  • setOnItemLongClickListener
  • setOnItemSelectedListener

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

fada21 avatar Mar 28 '18 16:03 fada21

What would the extensions do?

romainguy avatar Mar 28 '18 16:03 romainguy

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.

fada21 avatar Mar 29 '18 10:03 fada21

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
}

sohailehmad avatar Apr 02 '18 08:04 sohailehmad

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 avatar Apr 03 '18 11:04 fada21

@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 avatar Apr 03 '18 11:04 fada21

PR updated and ready for review.

fada21 avatar Apr 26 '18 10:04 fada21