Skip to content

Instantly share code, notes, and snippets.

@w2sv
Last active November 1, 2025 21:27
Show Gist options
  • Select an option

  • Save w2sv/b9bb9a598a17c249eb166d34f6502ad4 to your computer and use it in GitHub Desktop.

Select an option

Save w2sv/b9bb9a598a17c249eb166d34f6502ad4 to your computer and use it in GitHub Desktop.
Incorporating a processing sketch in jetpack compose
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
}
@w2sv
Copy link
Author

w2sv commented Nov 1, 2025

Works on configuration changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment