nil lakhay
nil lakhay

Reputation: 11

Android Kotlin Compose paste image from clipboard to the app

I need to implement feature that allows user to paste images from clipboard to my Android Kotlin Compose app, through textfield, and I need some help with that.

I saw people using BasicTextField2 and Modifier.receiveContent(), like was made in that blog: https://blog.shreyaspatil.dev/rich-media-input-from-the-keyboard-in-compose . But it don't work because BasicTextField2 is actually removed from Compose.Maybe there is some solution that works as of February 2025?

Upvotes: 0

Views: 60

Answers (1)

Ibrahim Zulfiqar
Ibrahim Zulfiqar

Reputation: 218

I don't know the reason but contentReceiver seems to work only when you use BasicTextField with TextFieldState. This is a bare minimum to make it work:

val images = remember { mutableStateListOf<Uri>() }

BasicTextField(
    state = rememberTextFieldState("BasicTextField with state"),
    modifier = Modifier
       .contentReceiver(object : ReceiveContentListener {
    override fun onReceive(transferableContent: TransferableContent): TransferableContent? {
        if (!transferableContent.hasMediaType(MediaType.Image)) {
            return transferableContent
        }
        val newImages = mutableListOf<Uri>()

        return transferableContent
            .consume { item ->
                // only consume this item if we can read an imageBitmap
                item.uri?.let {
                    newImages += it;
                    true
                } ?: false
            }
            .also {
                images.addAll(newImages)
            }
    }

})

Also this is how it is shown in the androidx.compose.foundation.samples.ReceiveContentFullSample.

contentReceiver does not seems to work if you use the BasicTextField value/onValueChange or the TextFieldValue variant.

Upvotes: 1

Related Questions