Skip to content

Instantly share code, notes, and snippets.

@oboenikui
Created June 27, 2023 17:42
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 oboenikui/e617f13cb085d3f2de0ca908f39c9575 to your computer and use it in GitHub Desktop.
Save oboenikui/e617f13cb085d3f2de0ca908f39c9575 to your computer and use it in GitHub Desktop.
Jetpack Composeの自動入力サンプル
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun LoginForm() {
var loginId by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val loginIdAutofillNode = AutofillNode(
autofillTypes = listOf(AutofillType.Username, AutofillType.EmailAddress),
onFill = { loginId = it }
)
val passwordAutofillNode = AutofillNode(
autofillTypes = listOf(AutofillType.Password),
onFill = { password = it }
)
val autofill = LocalAutofill.current
val autofillTree = LocalAutofillTree.current
autofillTree += loginIdAutofillNode
autofillTree += passwordAutofillNode
Column(
modifier = Modifier
.wrapContentHeight()
) {
OutlinedTextField(
placeholder = { Text("ログインID") },
value = loginId,
onValueChange = {
loginId = it
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
modifier = Modifier
.onGloballyPositioned {
loginIdAutofillNode.boundingBox = it.boundsInWindow()
}
.onFocusChanged { focusState ->
if (focusState.isFocused) {
autofill?.requestAutofillForNode(loginIdAutofillNode)
} else {
autofill?.cancelAutofillForNode(loginIdAutofillNode)
}
},
)
OutlinedTextField(
placeholder = { Text("パスワード") },
value = password,
onValueChange = {
password = it
},
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
),
modifier = Modifier
.onGloballyPositioned {
passwordAutofillNode.boundingBox = it.boundsInWindow()
}
.onFocusChanged { focusState ->
if (focusState.isFocused) {
autofill?.requestAutofillForNode(passwordAutofillNode)
} else {
autofill?.cancelAutofillForNode(passwordAutofillNode)
}
},
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment