I have a BasicTextField and I want it to focus by default when the screen opens and the keyboard to be close in all cases and not open.
How can I do that?
CodePudding user response:
One way is ... You can specify android:windowSoftInputMode="stateAlwaysHidden in manifest for that activity
Pros:
- It does the job to some extent without much
code
Cons:
- If the user presses on the edit text rapidly you can see the keyboard for some frames. Which may make users go crazy
- If you have other edit text which is editable in the same activity then you need to manually check for focus events and set this programmatically
Tip: If you are planning to allow users to only paste how about reading the data from the clipboard service and display it by default and make some UI changes to give options to users to go with that value or not ...
CodePudding user response:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Ui()
}
}
}
@Composable
fun Ui() {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Greeting()
}
}
}
@Composable
fun Greeting() {
var value by remember {
mutableStateOf("")
}
val localFocusManager = LocalFocusManager.current
val localSoftwareKeyboardController = LocalSoftwareKeyboardController.current
val focusRequester = remember { FocusRequester() }
TextField(
modifier = Modifier
.focusRequester(focusRequester)
.onFocusChanged { if(it.isFocused) localSoftwareKeyboardController?.hide() }
.focusable(),
value = value,
onValueChange = { value = it },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { localFocusManager.clearFocus() })
)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
Ui()
}
Just as in above code get current focus and clear it. or you can also hide keyboard using LocalSoftwareKeyboardController just like focusManager.
val localSoftwareKeyboardController = LocalSoftwareKeyboardController.current
....
keyboardActions = KeyboardActions(onDone = { localSoftwareKeyboardController?.hide() })
