Search code examples
androidandroid-fragmentskotlinclipboard

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


Solution

  • 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