Search code examples
androidkotlinandroid-contextandroid-jetpack-composekotlin-multiplatform

Copying to clipboard on Kotlin Multiplatform


I couldn't find anyone doing this so far so I'll try and properly state the issues I am facing.

I have a compose-ui module in the shared module of my KMP app. The compose-ui has a commonMain directory where all of the compose UI resides (screens that are shared between the desktop and the android app). Now the issue is, to copy the text to the clipboard (on Android) you need Context, which cannot be accessed in the commonMain, okay, no issues, I'll have to expect/ actual function @Composable copyToClipboard(text: string), but using the IconButton and its OnClick : () -> Unit which results in an error that @Composable can only be called from composable context. I am not sure how to go about this, I somehow need context to access the clipboard manager but I cannot access it nor pass it.


Solution

  • Something like this should work, it your androidMain:

    @Composable
    fun copyClipboardLambda(): () -> Unit {
        val context = LocalContext.current
        return {
            context.yourCopyFunc()
        }
    }
    

    In your View:

    @Composable
    fun View() {
        val copyClipboard = copyClipboardLambda()
        Box(
            modifier = Modifier.clickable {
                copyClipboard()
            }
        )
    }