当布尔值为真时,我如何进行屏幕更新?


if(isPlayerNearby) {
Text("Player $playerName is within range!")
Image(/*some image*/)
Button(onClick = { attack() }) {
Text(text = "ELIMINATE")
}
} else {
Text("No players nearby. Keep searching.")
Image(/*some OTHER image*/)
Button(onClick = { attack() }) { //This button should be DISABLED
Text(text = "ELIMINATE")
}
}

我有一个布尔变量,如果玩家在范围内,它就会变为真值,但我很困惑如何在满足这一要求时使屏幕实时更新。它应该从禁用切换到启用,反之亦然,当对方球员进入或超出范围。

下面是我们用来将isPlayerNearby设置为true的代码

private var endpointDiscoveryCallback: EndpointDiscoveryCallback = object :
EndpointDiscoveryCallback() {
override fun onEndpointFound(endpointId: String, info: DiscoveredEndpointInfo) {
toEndpointId = endpointId
// An endpoint was found. We request a connection to it.
Nearby.getConnectionsClient(context)
.requestConnection(getLocalUserName(), endpointId, connectionLifeCycleCallback)
.addOnSuccessListener {
run {
endpointFound()
//This is where we will set isPlayerNearby to true
Toast.makeText(applicationContext, endpointId, Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener { _ ->
//                Toast.makeText(applicationContext, "Could Not Connect", Toast.LENGTH_SHORT).show()
}
}
override fun onEndpointLost(endpointId: String) {
Toast.makeText(applicationContext, "Endpoint Lost", Toast.LENGTH_SHORT).show()
}
}

将布尔值设置为false将改变屏幕,但它不会实时更新-屏幕基本上需要重新构建才能看到结果。我相信我们必须使用状态,但我不太熟悉。

使用LiveData或StateFlow

val isPlayerNearby = MutableLiveData(false)

...
run {
endpointFound()
isPlayerNerby.postValue(true)
Toast.makeText(applicationContext,endpointId,Toast.LENGTH_SHORT)
.show()
}

在Fragment中观察liveData:

viewModel.isPlayerNearby.observe(viewLifecicleOwner) { isPlayerNearby ->

if(isPlayerNearby) {
Text("Player $playerName is within range!")
Image(/*some image*/)
Button(onClick = { attack() }) {
Text(text = "ELIMINATE") }
}else {
Text("No players nearby. Keep searching.")
Image(/*some OTHER image*/)
Button(onClick = { attack() }) { //This button should be DISABLED
Text(text = "ELIMINATE")
}
}

最新更新