icerockdev / moko-widgets

Multiplatform UI DSL with screen management in common code for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev
Apache License 2.0
387 stars 32 forks source link

Add listener from Widget-List #245

Closed Diy2210 closed 4 years ago

Diy2210 commented 4 years ago

How implement item list click listener? I create list on widgets like codelabs(MOKO Widgets #7 - lists on widgets), all works, but i dont understand how add listener from item click. Снимок экрана 2020-06-10 в 16 46 24

My code: Снимок экрана 2020-06-10 в 16 58 47 Снимок экрана 2020-06-10 в 16 58 54 My ViewModel: Снимок экрана 2020-06-10 в 16 59 42

UnitItem: Снимок экрана 2020-06-10 в 17 00 25

Tetraquark commented 4 years ago

You should to add clickable widget to the ServerUnitItem to handle clicks. And pass a callback to constructor of the unit class:

class ServerUnitItem(
    // ...
    private val clickListener: (ServerModel) -> Unit
) : WidgetsTableUnitItem<ServerModel>(itemId, server) {

    // ...

    override fun createWidget(data: LiveData<ServerModel>): UnitItemRoot {
        return with(theme) {
            clickable( // Wrap some widget into clickable widget
                onClick = { // Add onClick action
                    clickListener(data.value)
                },
                child = constraint(size = WidgetSize.WidthAsParentHeightWrapContent) {
                    // ...
                }
            ).let { UnitItemRoot.from(it) }
        }
    }
}

And then in the function of unit creation in the screen class you can handle clicks:

fun serversToTableUnits(servers: List<ServerModel>, viewModel: ServerViewModel): List<TableUnitItem> {
    return servers.map { server ->
        ServerUnitItem(
            // ...
            clickListener = { // here you can handle click to an unit
                viewModel.onClickToItem(it)
            }
        )
    }
}
Diy2210 commented 4 years ago

Tnx!!!