Arfmann
Arfmann

Reputation: 734

Kotlin Android - Copy to Clipboard from Fragment

I need to copy a text to clipboard, so I used a code that I already used in MainActivity:

 val myClipboard: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
 val myClip: ClipData

The problem is, this code works fine on an Activity but don't (obviously) on a Fragment.

on getSystemService:

Type inference failed: fun getSystemService(p0: Context, p1: Class): T? cannot be applied to (String)

on CLIPBOARD_SERVICE:

Type mismatch: inferred type is String but Context was expected

I've tried with

getSystemService(context!!, CLIPBOARD_SERVICE)

but doesn't works

Upvotes: 6

Views: 7886

Answers (4)

Leonardo Sibela
Leonardo Sibela

Reputation: 2189

Here's a neat extension fun for Kotlin users:

fun Fragment.copyToClipboard(text: String, label: String? = null) {
    (requireActivity().getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).apply {
        setPrimaryClip(ClipData.newPlainText(null, text))
    }
    displayToast(R.string.text_copied_to_clipboard, Toast.LENGTH_LONG)
}

Upvotes: 0

Parmesh
Parmesh

Reputation: 520

It's not a good idea to use force unwrap(!!) on context in Kotlin. In your fragment class you can use below code which is safe for any NPE and very clean.

(requireActivity().getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).apply {
        setPrimaryClip(ClipData.newPlainText("simple text", "some other text"))
    }

Happy Coding!

Upvotes: 11

Daniel Carracedo
Daniel Carracedo

Reputation: 85

In android x the constructor of getSystemService() changes.. Now u have to call to clipboard like this(You can Use activity!! or context!!)

var myClipboard = getSystemService(context!!, ClipboardManager::class.java) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("simple text", text)

myClipboard.setPrimaryClip(clip)

Upvotes: 4

Ivan Wooll
Ivan Wooll

Reputation: 4323

When your class is a fragment you can get a reference to its parent Activity by calling getActivity() in Java or just activity in Kotlin.

Using this approach you can change the code in your Activity to

val myClipboard: ClipboardManager = activity.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val myClip: ClipData

Upvotes: 11

Related Questions