0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidのコピー機能

Posted at

Androidでコピーを行う法方とその種類ををまとめる。

テキストをコピーする法方。

button.setOnClickListener {
    val greeting = "こんにちは"
    val clipboardManager: ClipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    clipboardManager.setPrimaryClip(ClipData.newPlainText("text", greeting))
    println("$greeting をコピーしました。")
}

画像をコピーする法方。画像をペーストできるアプリで反映される。アプリ内の画像であれば問題ないが、スマホ内の画像を取得する場合は別途パーミッションの処理が必要になる。

button.setOnClickListener {
    val uri: Uri = Uri.parse("content://media/images/media/12345")
    val clip = ClipData.newUri(requireContext().contentResolver, "image", uri)
    val clipboardManager: ClipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    clipboardManager.setPrimaryClip(clip)
}

HTML形式でコピーする法方。こちらはHTML形式のペーストが対応してるアプリだけ反映される。対応している場合は表示用テキストを貼り付けるか、HTMLを貼り付けるか選ぶことができる。

button.setOnClickListener {
    val clip = ClipData.newHtmlText(
        "Label",
        "表示用テキスト",
        "<h1>タイトル</h1>" + "<p>テキスト内容</p>"
    )
val clipboardManager: ClipboardManager = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(clip)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?