Skip to content

Instantly share code, notes, and snippets.

@fatemeh-afshari
Created February 18, 2023 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatemeh-afshari/dc7cc8231cad31955c73051968b34dd1 to your computer and use it in GitHub Desktop.
Save fatemeh-afshari/dc7cc8231cad31955c73051968b34dd1 to your computer and use it in GitHub Desktop.
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import com.test.composetextfieldselectiontest.ui.theme.ComposeTextFieldSelectionTestTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTextFieldSelectionTestTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CustomTextField()
}
}
}
}
}
@Composable
fun CustomTextField() {
val textFieldValue = remember {
mutableStateOf(TextFieldValue(""))
}
val interactionSource = remember { MutableInteractionSource() }
val isDoubleTap by interactionSource.collectIsDoubleTapAsState()
LaunchedEffect(isDoubleTap) {
val endRange = if (isDoubleTap) textFieldValue.value.text.length else 0
textFieldValue.value =
textFieldValue.value.copy(
selection = TextRange(
start = 0,
end = endRange
)
)
}
BasicTextField(
value = textFieldValue.value,
onValueChange = {
if (!isDoubleTap) {
textFieldValue.value = it
}
},
interactionSource = interactionSource
)
}
@Composable
fun InteractionSource.collectIsDoubleTapAsState(): State<Boolean> {
val isDoubleTap = remember { mutableStateOf(false) }
var firstInteractionTimeInMillis = 0L
LaunchedEffect(this) {
interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> {
val pressTimeInMillis = System.currentTimeMillis()
if (pressTimeInMillis - firstInteractionTimeInMillis <= 500L) {
firstInteractionTimeInMillis = 0
isDoubleTap.value = true
} else {
firstInteractionTimeInMillis = System.currentTimeMillis()
isDoubleTap.value = false
}
}
}
}
}
return isDoubleTap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment