So we have a MainActivity that’s mainly xml. But ...
# compose
m
So we have a MainActivity that’s mainly xml. But we’re starting to use compose for certain parts of it, and some of the things in there need to popup things like bottom sheet dialog. I was trying to write a declarative bridge that would do this, but i’m having trouble with the Preview annotation. I’m assuming we’re using FragmentActivity (because we always extend that in some indirect way). However Preview uses PreviewActivity which directly extends ComponentActivity. As a result, i can’t get access to the supportFragmentManager in order to show the dialog. Any suggestions? (code in thread)
Copy code
class BottomSheetDialogFragmentBridge: BottomSheetDialogFragment() {
    private var content: @Composable () -> Unit = { }
    var isCanceledOnTouchOutside: Boolean = true

    fun setContent(c: @Composable () -> Unit) {
        content = c
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return ComposeView(requireContext()).apply {
            setContent {
                content()
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            setCancelable(isCancelable)
            setCanceledOnTouchOutside(isCanceledOnTouchOutside)
        }
    }

}

@Composable
fun BottomSheetDialogBridge(
    tag: String,
    cancelable: Boolean,
    canceledOnTouchOutside: Boolean,
    content: @Composable () -> Unit
) {
    val context = LocalContext.current

    (context as? FragmentActivity)?.let { activity ->
        val dialog = remember { mutableStateOf<BottomSheetDialogFragment?>(null) }
        dialog.value = BottomSheetDialogFragmentBridge().apply {
            setContent(content)
            isCancelable = cancelable
            isCanceledOnTouchOutside = canceledOnTouchOutside
        }

        DisposableEffect(key1 = tag) {
            dialog.value?.show(activity.supportFragmentManager, tag)
            onDispose {
                dialog.value?.dismiss()
            }
        }
    }
}
i
Previews can't show dialogs anyways (as dialogs are separate windows - there's no window manager in previews). What exactly are you trying to preview?
m
@Ian Lake I was deploying the preview to the emulator. I also discovered i need to rework the code slightly anyway since i can’t use an inline fragment definition, but the same issue is present (i’m updating the code above)
c
@amaury is this something that can be handled in the Deploy Preview workflow?