Android 复制文本到剪切板
官方文档:https://developer.android.com/guide/topics/text/copy-paste#kotlin
private fun copyTextToClipboard(){
val clipboard = anchor.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
/**
* @param label User-visible label for the clip data.
* @param text The actual text in the clip.
*/
val clip: ClipData = ClipData.newPlainText("用户可见的标签", "复制的内容")
clipboard.primaryClip=clip
}
同样的可以复制Uri数据到剪切板,官方方法
private fun copyUriToClipboard() {
val clipboard = anchor.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// Creates a Uri based on a base Uri and a record ID based on the contact's last name
// Declares the base URI string
const val CONTACTS = "content://com.example.contacts"
// Declares a path string for URIs that you use to copy data
const val COPY_PATH = "/copy"
// Declares the Uri to paste to the clipboard
val copyUri: Uri = Uri.parse("$CONTACTS$COPY_PATH/$lastName")
...
// Creates a new URI clip object. The system uses the anonymous getContentResolver() object to
// get MIME types from provider. The clip object's label is "URI", and its data is
// the Uri previously created.
val clip: ClipData = ClipData.newUri(contentResolver, "URI", copyUri)
clipboard.primaryClip = clip
}
复制intent
private fun copyIntentToClipboard() {
val clipboard = anchor.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
// Creates the Intent
val appIntent = Intent(this, com.example.demo.myapplication::class.java)
...
// Creates a clip object with the Intent in it. Its label is "Intent" and its data is
// the Intent object created previously
val clip: ClipData = ClipData.newIntent("Intent", appIntent)
clipboard.primaryClip = clip
}