androidkotlinclipboardmanager

I get a "Val cannot be reasigned error" even though I assigned the variable as var?


I'm trying to add "copy to clipboard" functionality to an application. I added a setOnClickListener on the image button for copying and wrote the code below. I still get "val cannot be reassigned" error on "clipBoard.primaryClip = clip" line

            var clipBoard: ClipboardManager = getActivity()?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val StrEdtFirtname = etNoteDesc.text.toString()
            val clip = ClipData.newPlainText("Copied text",StrEdtFirtname)
            clipBoard.primaryClip = clip
            Toast.makeText(requireContext(), "Copied text", Toast.LENGTH_SHORT).show()
        }

Solution

  • Try with the following code.

    var clipBoard: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
         val StrEdtFirtname = etNoteDesc.text.toString()
        val clip = ClipData.newPlainText("Copied text",StrEdtFirtname)
        clipBoard.apply {
            setPrimaryClip(clip)
        }