android - 等待该片段可见的正确方法
问题描述
我正在为我的回合制游戏使用片段,在执行该片段中的任何代码之前,我如何确保片段是可见的并在这种异步函数中添加到上下文中?
fun respondToRematchInvitation(invitation : Invitation) {
if (winFragment.isVisible) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Accept invitation for rematch?")
builder.setMessage("Are you sure?")
builder.setPositiveButton("Yes") { _, _ ->
turnBasedMultiplayerClient.acceptInvitation(invitation.invitationId)
.addOnSuccessListener {
Log.d(TAG, "Invitation accepted succesfully")
isDoingTurn = false
gameFragment = GameFragment()
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, gameFragment).addToBackStack(null).commit()
onInitiateMatch(it) //error happens here
}.addOnFailureListener {
createFailureListener("Accepting invitation failed")
}
}
val dialog : AlertDialog = builder.create()
dialog.show()
现在onInitiateMatch(it)
我有一些修改gameFragment的代码,例如可能接收对手游戏数据和其他初始化。仅使用if (gameFragment.isVisible)
orif (gameFragment.isAdded)
是不够的,因为onInitiateMatch(it)
如果 if 语句返回 false,则可能不会执行这种方式的函数。
我应该为此使用线程吗?
解决方案
事实证明,执行supportFragmentManager.executePendingTransactions()
解决了问题,我首先认为这不是问题的解决方案。
推荐阅读
- blockchain - 实现子图来查询不同的区块链
- next.js - 使用 FaunaDB Dev 获取会话错误的 Next-Auth
- python - Matplotlib Plot 的标题和副标题不对齐
- java - 按对列表中的出现映射对象
- terraform - 使用“随机”资源(整数/字符串)时如何在 Terraform 中动态生成新变量?
- freemarker - Freemarker 函数字符串格式化
- mysql - 使用 concat 将一个简单的字符串、一个子查询和另一个简单的字符串放在一起
- java - 如何在java中使用正则表达式从url获取可选参数的值
- ruby - 错误:新模式破坏了与 rails 和 graphql 的向后兼容性
- python - 在 Python 的不同时间运行具有不同功能的函数