Home > Net >  Composable function as a private inner method in Activity
Composable function as a private inner method in Activity

Time:12-09

I have started to learn Jetpack compose. I was checking this sample from Google : https://github.com/android/compose-samples/blob/main/Crane/app/src/main/java/androidx/compose/samples/crane/home/MainActivity.kt

As you see MainScreen composable function is a method in the file and not an inner function in MainActivity class. MainScreen has not been used anywhere else. So why not define it as a private inner function in the Activity?

Would you please describe me the reason of that?

CodePudding user response:

They only need to be defined outside of a class if you plan on using the @Preview annotation, which allows Android Studio to render the composable in a preview pane. They should also be defined outside of the class if you plan on reusing the composable elsewhere in your app or make them generally reusable for other apps.

You can however define it as a inner function if you want to but you can't use the @Preview annotation. Nevertheless, if you don't plan on using preview and you have no reason to reuse the composable outside of the class, you can define it as an inner function. I've done that on many composables.

  • Related