我正在 Android 上开发浮动窗口,但遇到了问题。 因此,我的活动调用我的浮动类,该类创建视图并将其添加到窗口管理器,并带有显示并倒计时的计时器。在正常活动中尝试相同的代码时,它可以找到:S?
这是我的视图模型,保存着我的 mutableStateOf 值
class WicViewModel : ViewModel() {
private val TAG = "WicViewModel"
private val a = 10000L
private val b = 1000L
private var _input: Long by mutableStateOf(a)
var input: Long
get() = _input
set(value) {
if (value == _input) return
_input = value
}
fun start() {
val timer = object : CountDownTimer(a, b) {
override fun onTick(millisUntilFinished: Long) {
Log.d("MYLOG", "text updated programmatically")
input = millisUntilFinished
}
override fun onFinish() {
input = 0
}
}
timer.start()
}
}
这是我的课程,其中包含窗口管理器
class WicController constructor(val context: Context?, val viewModel: WicViewModel) {
private val TAG = "WicController"
private var windowManager: WindowManager? = null
private var wicView: View? = null
private lateinit var lifecycleOwner: CDOLifecycleOwner
fun show() {
if (context == null) return
val paramFloat = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
getWindowType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
)
paramFloat.gravity = Gravity.CENTER or Gravity.END
windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
val composeView = ComposeView(context.applicationContext)
composeView.setContent {
timerText(viewModel)
}
lifecycleOwner = CDOLifecycleOwner()
lifecycleOwner.performRestore(null)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
ViewTreeLifecycleOwner.set(composeView, lifecycleOwner)
ViewTreeSavedStateRegistryOwner.set(composeView, lifecycleOwner)
windowManager?.addView(composeView, paramFloat)
}
fun hide() {
windowManager?.removeView(wicView!!)
context?.let { Demo.startCalldorado(it) }
}
private fun getWindowType(): Int {
var windowType = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
windowType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
}
return windowType
}
@Composable
fun timerText(viewModel: WicViewModel){
Text(
text = (viewModel.input / 1000).toString(),
modifier = Modifier
.padding(bottom = 8.dp)
.fillMaxWidth(),
fontSize = 13.sp,
color = Color.White,
)
}}
我知道值正在改变,但组合并没有重新组合本身 有时它可能会改变,但非常随机。
我不知道我是否做错了,或者 compose 是否不是为窗口管理器/浮动窗口使用而设计的,但是我希望这里的一些人可以帮助我,因为我在网上找不到任何关于此的信息。
Jetpack Compose,使用自定义 Lifecycle/ViewModelStore/SavedStateRegistry Owner 时不会触发重组
这个答案会对你有帮助。
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)