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
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With