当前位置:网站首页>Keyboard processing in jetpack compose
Keyboard processing in jetpack compose
2022-07-29 07:45:00 【Programmer Xiao He SS】
Preface
Entering data is an important task in many applications . On devices without physical keyboards ( Most of them are in Android field ), The so-called soft ( Software ) The keyboard handles user input . Now? , You may wonder why we need to discuss these virtual peripherals . Shouldn't the operating system be taken care of ? Well, I mean , In terms of the user interface , The application expresses its desire to allow users to enter by displaying and configuring editable text fields . What else needs to be done ? This article introduces in detail Jetpack Compose How the application interacts with the keyboard .
Let's start with a simple Compose Hierarchy starts :
@Composable
fun KeyboardHandlingDemo1() {
var text by remember { mutableStateOf(TextFieldValue()) }
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom
) {
Box(
modifier = Modifier
.padding(16.dp)
.fillMaxSize()
.background(color = MaterialTheme.colors.primary)
.weight(1.0F),
contentAlignment = Alignment.BottomCenter
) {
Text(
modifier = Modifier.padding(bottom = 16.dp),
text = stringResource(id = R.string.app_name),
color = MaterialTheme.colors.onPrimary,
style = MaterialTheme.typography.h5
)
}
TextField(modifier = Modifier.padding(bottom = 16.dp),
value = text,
onValueChange = {
text = it
})
}
}

It looks good , Right ? Now? , Let's see what happens if the text field gets the focus .
This certainly doesn't look terrible , But it's not very good . Because the text field may attract the user's attention , It should be completely visible , Right ? ad locum , It is important to understand how the soft keyboard works with Activity And display Activity Windows of . Almost always ( from API Level 3 Start ) There is a manifest attribute ,windowSoftInputMode. It belongs to .
attribute
control Activity How does the main window of interact with the window containing the on-screen soft keyboard .
There are two main aspects :
- When activities become the focus of users , Whether the soft keyboard should be visible ?
- When some windows are covered by soft keyboard , Should be right Activity What adjustments are made to the main window of ?
In this paper , I will focus on the latter . For general introduction, please refer to processing input method visibility .
Now? , Let's look at the values related to adjustment .
adjustUnspecified Is the default setting for the behavior of the main window . Document theory :
It is not specified whether the active main window is resized to make room for the soft keyboard , Or whether to pan the contents of the window so that the current focus is visible on the screen . The system will automatically select one of the modes according to whether there is any layout view that can scroll the contents of the window . If there is such a view , The window will be resized , Suppose that scrolling can make all the contents of the window visible in a small area .
adjustResize:
Activity The main window of always resizes , To make room for the soft keyboard on the screen .
adjustPan:
Activity
The main window of does not resize to make room for the soft keyboard . contrary , The contents of the window will automatically pan , Therefore, the current focus will never be blocked by the keyboard , Users can always see what they are typing . This is usually not as desirable as resizing , Because the user may need to close the soft keyboard to reach and interact with the fuzzy part of the window .
If you recall the last screenshot , The window is obviously not resized . therefore , …
The system will automatically select one of the modes according to whether there is any layout view that can scroll the contents of the window .
… It doesn't seem to apply to Compose Applications . Of course, this is not surprising , Because use setContent { … }is According to the Compose The root view of the hierarchy ComposeView, it extends AbstractComposeView, It expands again ViewGroup( It cannot scroll ).
therefore , It's easy to fix : Just add
android:windowSoftInputMode="adjustResize"
To your label .

Multiple text fields
Let's look at another Compose hierarchy :
@Composable
fun KeyboardHandlingDemo2() {
val states = remember {
mutableStateListOf("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10")
}
val listState = rememberLazyListState()
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
itemsIndexed(states) { i, _ ->
OutlinedTextField(value = states[i],
modifier = Modifier.padding(top = 16.dp),
onValueChange = {
states[i] = it
},
label = {
Text("Text field ${i + 1}")
})
}
}
}

The user interface contains quite a few editable text fields . however , Through the above implementation , The user cannot use the soft keyboard to move to the next field , Instead, you must click and scroll . Fortunately, , We can use Compose Keyboard operations and options make this easy . Add the following lines to the pair In call to OutlinedTextField():
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
onNext = {
focusManager.moveFocus(FocusDirection.Down)
}
),
We configure the soft keyboard to display a special Next key ( ), And in In the callback ImeAction.Next Use one FocusManager( Belong to package androidx.compose.ui.focus) Navigation ( Moving the focus ) To ( vertical ) Next text field .
onNextKeyboardActions
val focusManager = LocalFocusManager.current
cool , Right ? however , One more thing we need to do . Our text fields belong to scrollable lists . Moving the focus does not change the currently visible part of the list . Here's how to do this :
listState.animateScrollToItem(i)
animateScrollToItem() Is a suspend function , So it should be called from a coroutine or another suspended function .
coroutineScope.launch {
listState.animateScrollToItem(i)
}
Last , To obtain the range of coprocessors in composable functions , You can use rememberCoroutineScope():
val coroutineScope = rememberCoroutineScope()
I also want to show you one thing : How to close the soft keyboard .
Show and hide the soft keyboard
The following screenshot shows my KeyboardHandlingDemo3() Composable function . It allows the user to input a number and calculate its square after pressing the calculation button or the special completion key on the soft keyboard . What you can't see in the screenshot : The soft keyboard is turned off . It may be that you want to display the complete user interface again after entering the data .
Let's look at the code :
@ExperimentalComposeUiApi
@Composable
fun KeyboardHandlingDemo3() {
val kc = LocalSoftwareKeyboardController.current
var text by remember { mutableStateOf("") }
var result by remember { mutableStateOf("") }
val callback = {
result = try {
val num = text.toFloat()
num.pow(2.0F).toString()
} catch (ex: NumberFormatException) {
""
}
kc?.hide()
}
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Row {
TextField(modifier = Modifier
.padding(bottom = 16.dp)
.alignByBaseline(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
callback()
}
),
value = text,
onValueChange = {
text = it
})
Button(modifier = Modifier
.padding(start = 8.dp)
.alignByBaseline(),
onClick = {
callback()
}) {
Text(stringResource(id = R.string.calc))
}
}
Text(
text = result,
style = MaterialTheme.typography.h4
)
}
}
The calculation takes place in callbacklambda in . ad locum , The soft keyboard also calls hide() example LocalSoftwareKeyboardController To close . Please note that , this API It's experimental , May be in the future Compose Changes in version .
We pass and to To configure a with Done Key numeric keypad .lambda It is called from the callback of the button , It belongs to .keyboardType = KeyboardType.NumberimeAction = ImeAction.DoneKeyboardOptions()callbackonClickonDoneKeyboardActions()
Conclusion
In this paper , I showed you how to communicate with Compose The soft keyboard in the application interacts . What I missed ? Do you want to follow up ? Please share your thoughts in the comments .
边栏推荐
- 国内数字藏品的乱象与未来
- Log4qt memory leak, use of heob memory detection tool
- [MySQL] - [subquery]
- MapReduce各阶段步骤
- QT connects two qslite databases and reports an error qsqlquery:: exec: database not open
- 【无标题】格式保存
- [summer daily question] Luogu p6461 [coci2006-2007 5] trik
- jdbc入门
- [summer daily question] Luogu p7760 [coci2016-2017 5] tuna
- The new generation of public chain attacks the "Impossible Triangle"
猜你喜欢

Amaze UI icon query

09 bloom filter

stm32 操作W25Q256 W25Q16 spi flash
![【暑期每日一题】洛谷 P7760 [COCI2016-2017#5] Tuna](/img/9a/f857538c574fb54bc1accb737d7aec.png)
【暑期每日一题】洛谷 P7760 [COCI2016-2017#5] Tuna

NFT 的 10 种实际用途

What is the use of chat robots? What type? After reading these, you will understand!

Cs61abc sharing session (VI) detailed explanation of program input and output - standard input and output, file, device, EOF, command line parameters

Segger's hardware anomaly analysis

LANDSCAPE

Up sampling deconvolution operation
随机推荐
What are the common error types and solutions of black box testing?
Cross domain problems when downloading webapi interface files
UPC 小C的王者峡谷
C# 之 volatile关键字解析
国内数字藏品的乱象与未来
蓝桥杯A组选数异或
Prometheus and grafana
[summer daily question] Luogu p6461 [coci2006-2007 5] trik
Use of gcc/g++
Blue Bridge Cup group a selection XOR
小D的刺绣
Mutationobserver document learning
Zip gzip tar compression Advanced Edition
《nlp入门+实战:第五章:使用pytorch中的API实现线性回归》
Joseph Ring problem
Write some DP
【暑期每日一题】洛谷 P4414 [COCI2006-2007#2] ABC
Jiamusi Market Supervision Bureau carried out special food safety network training on epidemic and insect prevention
智慧城市的应用挑战,昇腾AI给出了新解法
受欢迎的牛 G