The following code is the project.
I don't understand fully the code onExploreItemClicked = { launchDetailsActivity(context = this, item = it) }
in class MainActivity
.
The fun launchDetailsActivity
requires two paramaters which are Context
and ExploreModel
.
One of paramater is Context
which is assigned with this
, it's OK;
Another of paramater is ExploreMode
l which is assigned with it
, I don't know where the object ExploreModel
which is represented with it
is created, could you tell me?
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
ProvideWindowInsets {
ProvideImageLoader {
CraneTheme {
MainScreen(
onExploreItemClicked = { launchDetailsActivity(context = this, item = it) }
)
}
}
}
}
}
}
@Composable
fun MainScreen(onExploreItemClicked: OnExploreItemClicked) {
...
}
typealias OnExploreItemClicked = (ExploreModel) -> Unit
fun launchDetailsActivity(context: Context, item: ExploreModel) {
context.startActivity(createDetailsActivityIntent(context, item))
}
CodePudding user response:
The argument for onExploreItemClicked
is an implementation of (ExploreModel) -> Unit
. That function type is created via a lambda expression. In Kotlin, if a lambda has only one parameter then that parameter can be omitted and it's given the implicit name of it
.
So in this case, it
is the ExploreModel
instance passed to the function when invoked. Which instance that will be is likely dependent on which "explore item" is clicked on the screen. I haven't properly read all the code, but I did find this in ExploreSection.kt (by following the code starting with the construction of MainScreen
):
@OptIn(ExperimentalCoilApi::class)
@Composable
private fun ExploreItem(
modifier: Modifier = Modifier,
item: ExploreModel,
onItemClicked: OnExploreItemClicked ) {
Row(
modifier = modifier
.clickable { onItemClicked(item) }
.padding(top = 12.dp, bottom = 12.dp)
) {
/* REST OMITTED FOR BREVITY */
It accepts the OnExploreItemClicked
instance, as well as an ExploreModel
instance. Then, in the clickable
labmda, it invokes the OnExploreItemClicked
function:
.clickable { onItemClicked(item) }
And it passes in the associated ExploreModel
instance. Of course, that only tells you where it
(that we previously talked about) gets its value, but it doesn't tell you where the ExploreModel
instance is actually created. You'd have to explore the code more to see where ExploreItem
is called, and where it gets the model (I believe it at least comes from the view model).
Note if you don't want to use the implicit it
, then you can give the parameter an explicit name (and type, if wanted). For example:
MainScreen(
onExploreItemClicked = { model: ExploreModel -> launchDetailsActivity(context = this, item = model) }
)
Further reading: