Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 523
Arfmann Avatar asked Nov 30 '22 13:11

Arfmann


2 Answers

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
like image 192
Ivan Wooll Avatar answered Dec 03 '22 23:12

Ivan Wooll


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!

like image 41
Parmesh Avatar answered Dec 04 '22 00:12

Parmesh