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

84 Views Asked by At

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()
        }
1

There are 1 best solutions below

0
Dharmender Manral On BEST ANSWER

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)
    }