How to copy text to clipboard styled with Typeface?

188 Views Asked by At

I want to copy the styled form of a sample text to the clipboard after styling with the Typeface, but it is copied as unstyled when copying. How to copy styled text?

binding.buttonStyle.setOnClickListener {
            val textStyleSample = TextStyle(
                0,
                "Sample Text",
                CustomFontStyle.rubik_pixels_regular
            )

            val spannable = SpannableString(textStyleSample.text)
            spannable.setSpan(
                makeStyleForText(textStyleSample),
                0,
                textStyleSample.text.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            val clipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText(
                "styledText",
                spannable.toString()
            )
            clipboardManager.setPrimaryClip(clipData)
        }

data class TextStyle(
    val id: Int, var text: String, var customFontStyle: CustomFontStyle
)

enum class CustomFontStyle {
    rubik_pixels_regular,
    inspiration_regular,
}

private fun makeStyleForText(textStyle: TextStyle): Typeface {
        return Typeface.createFromAsset(
            requireContext().assets,
            "${textStyle.customFontStyle}.ttf"
        )
    }
1

There are 1 best solutions below

0
Ahmet Kaan On

You can copy styled string with html but of course you cant copy html, you can copy only string values so maybe you can try to convert a html to string and then convert it again. Let me give an example. I have a bold text. Lets call it

This is my bold text

If you copy this directly, You will find its original version like;

This is my bold text

But if you turn it to the html like;

mySpannedText.html

when you print it, it will looks something like;

<b>This is my bold text</b>

And when you paste it anywhere it looks like this too. But you can turn it to a bold text again. If we assume that you define it in a variable named "sourceString" then you can turn it like;

Html.fromHtml(sourceString)

In your code, you can store spanned string in clipboard with those html turning. But in paste part, you should write some code which uses "Html.fromHtml()". I dont have so much information about Clipboard Manager but i just want to inform you about this.