gpt4 book ai didi

android - Jetpack Compose,使用自定义 Lifecycle/ViewModelStore/SavedStateRegistry Owner 时不会触发重组

转载 作者:行者123 更新时间:2023-12-05 03:24:00 25 4
gpt4 key购买 nike

我正在尝试创建一个叠加层并将 View 附加到 WindowManager,我已经通过创建一个实现 Lifecycle/ViewModelStore/SavedStateRegistry Owner 的类设法做到了这一点。但出于某种原因,每当我尝试使用 MutableState 或 MutableStateFlow 重组以任何方式显示对话框/更改 UI 时,都不会触发。

有没有人尝试过做这样的事情并设法找到触发重组的解决方案?

这就是我尝试创建和插入 View 的方式:

@SuppressLint("InflateParams")
fun showOverlay() {
synchronized(lock) {
if (overlay != null || overlay?.parent != null) {
return
}
val viewModel = OverlayViewModel(context.applicationContext as Application)
var scope: CoroutineScope? = null
overlay = ComposeView(context).apply {
setContent {
Overlay(viewModel)
}
}
drawOverLifecycleOwner = DrawOverLifecycleOwner()
drawOverLifecycleOwner?.attachToDecorView(overlay)
val params =
WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT
)
params.gravity = Gravity.TOP or Gravity.START
Log.i("ScreenLocker", "Inserting overlay")
ContextCompat.getMainExecutor(context).execute {
drawOverLifecycleOwner?.onCreate()
windowManager.addView(overlay, params)
}
}
}

这是自定义的 LifecycleOwner:

import android.view.View
import androidx.lifecycle.*
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.ViewTreeSavedStateRegistryOwner

class DrawOverLifecycleOwner : LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner {

fun onCreate() {
savedStateRegistryController.performRestore(null)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}

fun onResume() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}

fun onPause() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
}

fun onDestroy() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
savedStateRegistryController.performSave(Bundle())
store.clear()
}

/**
Compose uses the Window's decor view to locate the
Lifecycle/ViewModel/SavedStateRegistry owners.
Therefore, we need to set this class as the "owner" for the decor view.
*/
fun attachToDecorView(decorView: View?) {
if (decorView == null) return

ViewTreeLifecycleOwner.set(decorView, this)
ViewTreeViewModelStoreOwner.set(decorView, this)
ViewTreeSavedStateRegistryOwner.set(decorView, this)
}

// LifecycleOwner methods
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)

override fun getLifecycle(): Lifecycle = lifecycleRegistry

// ViewModelStore methods
private val store = ViewModelStore()
override fun getViewModelStore(): ViewModelStore = store

// SavedStateRegistry methods
private val savedStateRegistryController = SavedStateRegistryController.create(this)
override val savedStateRegistry: SavedStateRegistry
get() = savedStateRegistryController.savedStateRegistry
}

这是叠加层:

@Composable
fun Overlay(viewModel: OverlayViewModel = viewModel()) {
val showDialog = remember { MutableStateFlow(false) }
AppTheme {
Logger.info("Recomposition triggered")
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
) {
val (dialog) = createRefs()
Box(modifier = Modifier.fillMaxSize()) {
Text(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(top = 25.dp, end = 15.dp),
text = "© 2022",
color = Color.White
)
Column(
modifier = Modifier.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
painter = painterResource(R.drawable.logo),
contentDescription = "Logo",
contentScale = ContentScale.Fit,
)
Text(
modifier = Modifier.padding(bottom = 25.dp),
text = "Overlay Text",
textAlign = TextAlign.Center,
color = Color.White,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.headlineMedium
)
LazyRow {
items(LockService.whitelistedApps) { app ->
Button(
onClick = { viewModel.launchApp(app) },
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent
)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
viewModel.getPackageIcon(app)?.apply {
Image(
this.asImageBitmap(),
contentDescription = "App Icon"
)
}
Text(
text = viewModel.getPackageLabel(app),
color = Color.White
)
}
}
}
}
}
IconButton(
modifier = Modifier
.align(Alignment.BottomStart)
.padding(bottom = 15.dp, start = 15.dp),
onClick = {
Logger.info("Trying to show dialog, showDialogValue = ${showDialog.value}")
showDialog.tryEmit(true)
}
) {
Icon(
imageVector = Icons.Default.Info,
contentDescription = "Info Dialog Icon",
tint = Color.White
)
}
}
if (showDialog.collectAsState().value) {
InfoDialog(showDialog, Modifier.constrainAs(dialog) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
})
}
}
}
}

@Preview
@Composable
fun OverlayPreview() {
AppTheme {
Overlay(OverlayViewModel(Application()))
}
}

最佳答案

嘿,我发现我的实现中存在问题,它可能与您的相同。

当你强制设置 lifecycleOwner 到 ComposeView 时,你是否也设置了 ON_START 事件?在我的版本中,它丢失了,当我完成后,可组合项开始响应新状态。

        val viewModelStore = ViewModelStore()
lifecycleOwner.performRestore(null)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START)
ViewTreeLifecycleOwner.set(composeView, lifecycleOwner)
ViewTreeViewModelStoreOwner.set(composeView) { viewModelStore }
it.setViewTreeSavedStateRegistryOwner(lifecycleOwner)

关于android - Jetpack Compose,使用自定义 Lifecycle/ViewModelStore/SavedStateRegistry Owner 时不会触发重组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72379865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com