当前位置:网站首页>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 .
边栏推荐
- RoBERTa:A Robustly Optimized BERT Pretraining Approach
- cs61abc分享会(六)程序的输入输出详解 - 标准输入输出,文件,设备,EOF,命令行参数
- Space shooting Lesson 17: game over (end)
- UPC 小C的王者峡谷
- 【暑期每日一题】洛谷 P6461 [COCI2006-2007#5] TRIK
- Use custom annotations to verify the size of the list
- Use of gcc/g++
- 状态机dp(简单版)
- 09 bloom filter
- gin abort不能阻止后续代码的问题
猜你喜欢
Realize the effect of changing some colors of a paragraph of text
分析25个主要DeFi协议的路线图 预见DeFi未来的七大趋势
美智光电IPO被终止:年营收9.26亿 何享健为实控人
Log4qt memory leak, use of heob memory detection tool
09 bloom filter
Jianmu continuous integration platform v2.5.2 release
cs61abc分享会(六)程序的输入输出详解 - 标准输入输出,文件,设备,EOF,命令行参数
[summer daily question] Luogu p6461 [coci2006-2007 5] trik
佳木斯市场监管局开展防疫防虫害专题食品安全网络培训
Android面试题 | 怎么写一个又好又快的日志库?
随机推荐
Halcon installation and testing in vs2017, DLL configuration in vs2017
智慧城市的应用挑战,昇腾AI给出了新解法
MySQL 45 讲 | 07 行锁功过:怎么减少行锁对性能的影响?
You study, I reward, 21 day learning challenge | waiting for you to fight
写点dp
@RequestMapping 用法详解
信用卡购物积分
Write some DP
准备esp32环境
[summer daily question] Luogu P6500 [coci2010-2011 3] zbroj
Write some DP
What are the answers about older bloggers?
Output 1234 three digits without repetition
How can electronic component trading enterprises solve warehouse management problems with ERP system?
程序的静态库与动态库的区别
Ionicons icon Encyclopedia
String class
【暑期每日一题】洛谷 P4413 [COCI2006-2007#2] R2
How to get to the deep-water area when the industrial Internet goes?
分析25个主要DeFi协议的路线图 预见DeFi未来的七大趋势