有Column
一个按钮列表,您需要要求将焦点放在列表中的第一个按钮上,我是这样做的
...
var modifier: Modifier = Modifier
.height(96.toDpWithOffset)
.width(520.toDpWithOffset)
if (idx == 0) {
modifier = modifier.focusRequester(focusRequester)
}
Button(modifier = modifier...
...
也就是说,如果这是第一个按钮,则添加focusRequester
到modifier
问题是这样的:视觉上它可以像这样缩短
...
Button(
modifier = Modifier
.height(96.toDpWithOffset)
.width(520.toDpWithOffset)
.apply {
if (idx == 0) {
this.focusRequester(focusRequester)
}
}
...
但由于某种原因它会引发错误
Process: ca.bellmedia.cravetv.debug, PID: 27984
kotlinx.coroutines.CompletionHandlerException: Exception in completion handler InvokeOnCompletion@b5280d2[job@9cd05a3] for StandaloneCoroutine{Completed}@9cd05a3
at kotlinx.coroutines.JobSupport.completeStateFinalization(JobSupport.kt:322)
at kotlinx.coroutines.JobSupport.tryFinalizeSimpleState(JobSupport.kt:297)
at kotlinx.coroutines.JobSupport.tryMakeCompleting(JobSupport.kt:860)
at kotlinx.coroutines.JobSupport.makeCompletingOnce$kotlinx_coroutines_core(JobSupport.kt:832)
at kotlinx.coroutines.AbstractCoroutine.resumeWith(AbstractCoroutine.kt:100)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:46)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
at android.os.Handler.handleCallback(Handler.java:958)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:205)
at android.os.Looper.loop(Looper.java:294)
at android.app.ActivityThread.main(ActivityThread.java:8177)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [androidx.compose.ui.platform.MotionDurationScaleImpl@99dc6cc, androidx.compose.runtime.BroadcastFrameClock@887fd15, StandaloneCoroutine{Completed}@9cd05a3, AndroidUiDispatcher@441582a]
Caused by: java.lang.IllegalStateException:
FocusRequester is not initialized. Here are some possible fixes:
1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
2. Did you forget to add a Modifier.focusRequester() ?
3. Are you attempting to request focus during composition? Focus requests should be made in
response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }
我在这里缺少什么?
尝试按如下方式重现您的代码
他工作。但如果你
let
用它替换它apply
,它会崩溃并出现与你相同的错误。顺便说一句,这就是错误所说的
2. Did you forget to add a Modifier.focusRequester() ?
原因:所有方法
Modifier'а
都返回一个新对象,而不是向现有对象添加一些内容。使用let
或任何其他方法会给你返回一个新的Modifier