Skip to content

Commit f875462

Browse files
committed
Code snippet for Compose doc at https://developer.android.com/quick-guides/content/animate-text?hl=en (Animate text character-by-character).
This commit slightly modifies (makes buildable in our repo) the existing code on the current DAC page. That code, in turn, was BNR's simplified version of Xoogler astamato's Medium article at https://medium.com/androiddevelopers/effective-state-management-for-textfield-in-compose-d6e5b070fbe5
1 parent 351fcb4 commit f875462

File tree

1 file changed

+54
-0
lines changed
  • compose/snippets/src/main/java/com/example/compose/snippets/text

1 file changed

+54
-0
lines changed

compose/snippets/src/main/java/com/example/compose/snippets/text/TextSnippets.kt

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import androidx.compose.material3.OutlinedTextField
3838
import androidx.compose.material3.Text
3939
import androidx.compose.material3.TextField
4040
import androidx.compose.runtime.Composable
41+
import androidx.compose.runtime.derivedStateOf
4142
import androidx.compose.runtime.getValue
4243
import androidx.compose.runtime.mutableStateOf
4344
import androidx.compose.runtime.remember
@@ -839,3 +840,56 @@ private val firaSansFamily = FontFamily()
839840

840841
val LightBlue = Color(0xFF0066FF)
841842
val Purple = Color(0xFF800080)
843+
844+
// [START android_compose_text_auto_format_phone_number_validatetext]
845+
@Composable
846+
fun ValidateInput () {
847+
class EmailViewModel : ViewModel() {
848+
var email by mutableStateOf("")
849+
private set
850+
851+
val emailHasErrors by derivedStateOf {
852+
if (email.isNotEmpty()) {
853+
// Email is considered erroneous until it completely matches EMAIL_ADDRESS.
854+
!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
855+
} else {
856+
false
857+
}
858+
}
859+
860+
fun updateEmail(input: String) {
861+
email = input
862+
}
863+
}
864+
865+
@Composable
866+
fun ValidatingInputTextField(
867+
email: String,
868+
updateState: (String) -> Unit,
869+
validatorHasErrors: Boolean
870+
) {
871+
val viewModel = EmailViewModel()
872+
OutlinedTextField(
873+
modifier = Modifier
874+
.fillMaxWidth()
875+
.padding(10.dp),
876+
value = email,
877+
onValueChange = updateState,
878+
label = { Text("Email") },
879+
isError = validatorHasErrors,
880+
supportingText = {
881+
if (validatorHasErrors) {
882+
Text("Incorrect email format.")
883+
}
884+
}
885+
)
886+
887+
888+
ValidatingInputTextField(
889+
email = viewModel.email,
890+
updateState = { input -> viewModel.updateEmail(input) },
891+
validatorHasErrors = viewModel.emailHasErrors
892+
)
893+
}
894+
}
895+
// [END android_compose_text_auto_format_phone_number_validatetext]

0 commit comments

Comments
 (0)