首页 > 解决方案 > 等待该片段可见的正确方法

问题描述

我正在为我的回合制游戏使用片段,在执行该片段中的任何代码之前,我如何确保片段是可见的并在这种异步函数中添加到上下文中?

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,则可能不会执行这种方式的函数。

我应该为此使用线程吗?

标签: androidandroid-fragmentskotlingoogle-play-services

解决方案


事实证明,执行supportFragmentManager.executePendingTransactions()解决了问题,我首先认为这不是问题的解决方案。


推荐阅读