Last active
November 1, 2025 21:27
-
-
Save w2sv/b9bb9a598a17c249eb166d34f6502ad4 to your computer and use it in GitHub Desktop.
Incorporating a processing sketch in jetpack compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.view.View | |
| import android.widget.FrameLayout | |
| import androidx.compose.runtime.Composable | |
| import androidx.compose.runtime.saveable.rememberSaveable | |
| import androidx.compose.ui.Modifier | |
| import androidx.compose.ui.viewinterop.AndroidView | |
| import androidx.fragment.app.FragmentActivity | |
| import androidx.fragment.app.commitNow | |
| import processing.android.PFragment | |
| import processing.core.PApplet | |
| import java.util.UUID | |
| @Composable | |
| fun ProcessingSketch(sketch: PApplet, modifier: Modifier = Modifier) { | |
| val fragmentTag = rememberSaveable { "PFragment_${UUID.randomUUID()}" } | |
| AndroidView( | |
| factory = { context -> FrameLayout(context).apply { id = View.generateViewId() } }, | |
| update = { view -> | |
| val activity = view.context.findActivity() as? FragmentActivity | |
| ?: error("FragmentActivity not found for ProcessingSketch") | |
| val fragmentManager = activity.supportFragmentManager | |
| fragmentManager.commitNow(allowStateLoss = true) { | |
| // Remove existing fragment, if present | |
| fragmentManager.findFragmentByTag(fragmentTag)?.let { existingFragment -> | |
| remove(existingFragment) | |
| } | |
| // Add new fragment | |
| val fragment = PFragment(sketch) | |
| replace(view.id, fragment, fragmentTag) | |
| } | |
| }, | |
| modifier = modifier | |
| ) | |
| } | |
| fun Context.findActivity(): Activity? = | |
| when (this) { | |
| is Activity -> this | |
| is ContextWrapper -> baseContext.findActivity() | |
| else -> null | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works on configuration changes