- Java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
public class ExtraUtil {
public static void copy2Clipboard(Context context, String text) {
if (context == null || text == null) {
return;
}
if (Build.VERSION.SDK_INT >= 11) {
ClipboardManager clipboardManager = (ClipboardManager)
context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText(null, text);
clipboardManager.setPrimaryClip(clipData);
} else {
android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager)
context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(text);
}
}
}
- Kotlin
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
object ExtraUtil {
fun copy2Clipboard(context: Context?, text: String?) {
if (context == null || text == null) {
return
}
if (Build.VERSION.SDK_INT >= 11) {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE)
as ClipboardManager
val clipData = ClipData.newPlainText(null, text)
clipboardManager.primaryClip = clipData
} else {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE)
as android.text.ClipboardManager
clipboardManager.text = text
}
}
}
从这个例子中可以发现 Kotlin 语法的一些特点。
Kotlin 在 Google I/O 2017 大会中被确立为 Android 官方开发语言。去了解