我最近遇到一个错误,导致任何 Jetpack Compose 预览无法显示,如下所示:
Failed to instantiate one or more classes
The following classes could not be instantiated:
-androidx.compose.ui.tooling.ComposeViewAdapter(Open Class, Show Exception, Clear Cache)
if this is an unexpected error you can also try to build the project, then manually refresh the layout
java.lang.NoClassDefFoundError: Could not initialize class androidx.customview.poolingcontainer.PoolingContainer
at androidx.compose.ui.platform.ViewCompositionStrategy$DisposeOnDetachedFromWindowIfNotInPoolingContainer.installFor(ViewCompositionStrategy.android.kt:97)
at androidx.compose.ui.platform.AbstractComposeView.<init>(ComposeView.android.kt:123)
at androidx.compose.ui.platform.ComposeView.<init>(ComposeView.android.kt:392)
at androidx.compose.ui.platform.ComposeView.<init>(ComposeView.android.kt:388)
at androidx.compose.ui.tooling.ComposeViewAdapter.<init>(ComposeViewAdapter.kt:131)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:339)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:176)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:136)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:301)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:417)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:428) …
Run Code Online (Sandbox Code Playgroud) android android-studio android-jetpack-compose android-jetpack-compose-preview
当键盘的 KeyboardType 设置为 KeyboardType.Number 时,我当前无法捕获用户输入到文本字段中。
如果键盘设置为 KeyboardType.Text,则文本字段会按预期更新,但是当设置为 KeyboardType.Number 时,文本字段将无法更新。
为什么是这样?以及如何更改我的代码,以便在单击文本字段时显示数字键盘,并且在按下数字时在文本字段中更新相关数字。
以下代码不会更新文本字段(当设置为 KeyboardType.Number 时)...
@Composable
fun MyNumberField() {
var text = remember { mutableStateOf("")}
val change : (String) -> Unit = { it ->
value.value = it
}
TextField(
value = text.value,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
onValueChange = change
)
}
Run Code Online (Sandbox Code Playgroud)
以下代码确实更新了文本字段(当设置为 KeyboardType.Text 时)...
@Composable
fun MyNumberField() {
var text = remember { mutableStateOf("")}
val change : (String) -> Unit = { it ->
text.value = it …
Run Code Online (Sandbox Code Playgroud) android user-input textfield android-jetpack android-jetpack-compose