2
1

TextViewをコピーできるようにするには(XML&Compose)

Posted at

XML

XMLのTextViewに以下のコードを追加します

android:textIsSelectable="true"

これだけでテキストのコピーが可能になります
コード上から変更する場合にはsetTextIsSelectable()を使用することで変更可能です。

ただしこれをtrueにすることでfocusable, focusableInTouchMode, clickable, longClickableのフラグも同じくtrueになるのでコード上から変更する際には注意が必要です。

Compose

テキストをSelectionContainerでラップすることでコピー可能になります

@Composable
fun SelectableText() {
    SelectionContainer {
        Text("This text is selectable")
    }
}

また、コピー可能テキストの中の一部のみコピー不可にしたい場合はDisableSelectionでラップすることで実現できます。

@Composable
fun PartiallySelectableText() {
    SelectionContainer {
        Column {
            Text("This text is selectable")
            Text("This one too")
            Text("This one as well")
            DisableSelection {
                Text("But not this one")
                Text("Neither this one")
            }
            Text("But again, you can select this one")
            Text("And this one too")
        }
    }
}

出典

2
1
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
2
1