Android 复制文本到系统剪切板

发布时间: 2022-11-06 22:23:39 作者: 大象笔记

需求

我正在开发的一个 Android App,其主要功能就是将扫描出来的蓝牙设备信息,自动复制到手机剪切板。 然后复制到其他需要配置的地方。

例如,点击蓝牙设备的 Mac 地址,自动写入剪切板。

复杂的实现

看了官方文档,发现要实现这么个简单的功能,远比想象中复杂。

https://developer.android.com/develop/ui/views/touch-and-input/copy-paste

kotlin 实现代码

在 activity 中调用:

fun copyText(text:String) {
    val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
    // When setting the clip board text.
    clipboardManager.setPrimaryClip(ClipData.newPlainText("", text))
    // Only show a toast for Android 12 and lower.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2)
        Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
}

在 fragment 中调用

fun copyText(text:String) {
    val clipboardManager = activity?.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
    // When setting the clip board text.
    clipboardManager.setPrimaryClip(ClipData.newPlainText("", text))
    // Only show a toast for Android 12 and lower.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2)
        Toast.makeText(activity, "Copied", Toast.LENGTH_SHORT).show()
}

在 recycler view adapter 的 view holder 中调用。 其中增加了一个参数 view,这里传入随便一个 text view 或者 button 都可以。

private fun copyText(text: String, view: View) {
	val clipboardManager =
		view.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
	// When setting the clip board text.
	clipboardManager.setPrimaryClip(ClipData.newPlainText("", text))
	// Only show a toast for Android 12 and lower.
	if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2)
		Toast.makeText(view.context, "Copied", Toast.LENGTH_SHORT).show()
}

封装

由于 app 中,多处要用到剪切板功能,还是封装在一个 object 比较方便代码更新。

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.widget.Toast

object Utils {
    fun copyText(text: String, context: Context) {
        val clipboardManager =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // When setting the clip board text.
        clipboardManager.setPrimaryClip(ClipData.newPlainText("", text))
        // Only show a toast for Android 12 and lower.
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2)
            Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
    }
}

例如,在 recycler view adapter 的 view holder 中调用。

address.setOnClickListener {
    Utils.copyText(address.text as String, address.context)
}

参考

我是一名山东烟台的开发者,联系作者