Skip to content

Instantly share code, notes, and snippets.

@raamcosta
raamcosta / ComposeRenderer.kt
Last active December 6, 2023 09:59
Render a Composable without showing it on screen
class ComposeRenderer(
private val activity: ComponentActivity
) {
suspend fun render(
content: @Composable () -> Unit
): Result<Bitmap> {
val completableBitmap = CompletableDeferred<Result<Bitmap>>()
activity.awaitWindowToken()
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
data class ProfileScreenNavArgs(
val id: Long,
val groupName: String?
)
//Then in the @Destination:
@Destination(
navArgsDelegate = ProfileScreenNavArgs::class
)
// Just as an example of something you might want to send to some destinations
val scaffoldState = rememberScaffoldState()
DestinationsNavHost(
navGraph = NavGraphs.root
) {
composable(SomeScreenDestination) { //this: DestinationScope<SomeScreenDestination.NavArgs>
SomeScreen(
arg1 = navArgs.arg1, // navArgs is a lazily evaluated `SomeScreenDestination.NavArgs` instance, field of `DestinationScope`
navigator = destinationsNavigator, // destinationsNavigator is a `DestinationsNavigator` (also lazily evaluated)
@Destination(start = true)
@Composable
fun LoginScreen(
navigator: DestinationsNavigator
) {
/*...*/
Button (onClick = { navigator.navigate(HomeScreenDestination) }
/*...*/
}
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = Screens.Login.route
) {
composable(route = Screens.Login.route) {
LoginScreen(
navigateToHome = {
navController.navigate(Screens.Home.route)
}
// Screen routes ____________________________
sealed class Screens(val route: String) {
object Login : Screens("login")
object Home : Screens("home")
object Profile : Screens("profile/{id}?isEditable={isEditable}")
object Search : Screens("search?query={query}")
}
@Composable
fun LoginScreen(
navigateToHome: () -> Unit
) {
/*...*/
Button (onClick = navigateToHome) {
/*...*/
}
@Composable
@raamcosta
raamcosta / UiText.kt
Created October 6, 2021 23:00
UiText.kt
sealed class UiText {
class DynamicText(val text: String) : UiText()
class ResourceText(@StringRes val stringRes: Int) : UiText()
}
fun UiText.getString(context: Context) = when (this) {
is UiText.DynamicText -> text
is UiText.ResourceText -> context.getString(stringRes)
@raamcosta
raamcosta / ComposeDestinationsExample.kt
Last active September 28, 2021 01:01
Using Compose Destinations
//region Screen Composables
@Destination(route = "profile")
@Composable
fun ProfileScreen(
id: String,
isEditable: Boolean = false
) {/*...*/}
@Destination(route = "login", start = true)
@Composable