使用 Jetpack Compose 在 Android 软键盘中实现 IME 操作按钮
在Android中, IME(Input Method Action)动作按钮是软键盘上的一个按键,代表可以显示的不同动作。在下图中,我们找到了两种不同类型的 IME 操作按钮。
在下图中,您可以看到可以在软键盘上的 IME 操作按钮中显示的不同类型的操作。
因此,在本文中,我们将向您展示如何使用 Jetpack Compose 在 Android 软键盘中实现 IME 操作按钮。 IDE 准备就绪后,请按照以下步骤操作。
分步实施
第 1 步:在 Android Studio 中创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。选择模板时,选择Empty Compose Activity 。如果您没有找到此模板,请尝试将 Android Studio 升级到最新版本。我们在Kotlin中演示了该应用程序,因此请确保在创建新项目时选择 Kotlin 作为主要语言。
第 2 步:使用 MainActivity.kt 文件
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
Kotlin
package com.geeksforgeeks.jcimeactions
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import com.geeksforgeeks.jcimeactions.ui.theme.JCImeActionsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Calling the composable function to
// display element and its contents
MainContent()
}
}
}
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent() {
Scaffold(
topBar = { TopAppBar(title = { Text("GFG | IME Actions", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
content = { MyContent() }
)
}
// Creating a composable function
// to create a TextField
// Calling this function as content
// in the above function
@Composable
fun MyContent(){
// declaring a string variable to
// store the TextField input value
var mInput by remember { mutableStateOf("") }
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
// Creating a textField
// setting keyboard options
// IME action as Done
TextField(
value = mInput,
onValueChange = { mInput = it },
label = { Text("Enter Input") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
)
}
}
// For displaying preview in the
// Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}
输出:
您可以看到我们能够将软键盘上的 IME 操作按钮更改为完成。