HelloCW
HelloCW

Reputation: 2285

How to remove OnPrimaryClipChangedListener of ClipboardManager in Kotlin?

I use the following code to monitor the change of clipboard, I hope to remove the monitor when I finish the operation.

But clipboard.removePrimaryClipChangedListener { } required to pass parameters, how can I do?

Code

 btnMonitor.setOnClickListener {
         val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

         clipboard.addPrimaryClipChangedListener {
             if (clipboard.hasPrimaryClip() && clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) ) {
                 var pasteData: String = ""
                 val item = clipboard.primaryClip.getItemAt(0)
                 pasteData = item.text.toString()

                 toast("Hi - " + pasteData)
             }
         }  

         clipboard.removePrimaryClipChangedListener {  }  //I don't know how to pass paramaters        
     }

Upvotes: 2

Views: 841

Answers (1)

Onik
Onik

Reputation: 19969

In order to remove OnPrimaryClipChangedListener you need a reference to lambda you "set" before. Try re-organise the code as follows.

private val lambda = ClipboardManager.OnPrimaryClipChangedListener {

    if (clipboard.hasPrimaryClip() && clipboard.primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) ) {
        var pasteData: String = ""
        val item = clipboard.primaryClip.getItemAt(0)
        pasteData = item.text.toString()

        toast("Hi - " + pasteData)
    }
}

Later you can add and remove the lambda with clipboard.addPrimaryClipChangedListener(lambda) and clipboard.removePrimaryClipChangedListener(lambda)

Upvotes: 3

Related Questions