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")
}
}
}