FragmentTransaction隐藏/显示有时不起作用 [英] FragmentTransaction hide/show doesn't work sometimes

查看:653
本文介绍了FragmentTransaction隐藏/显示有时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有底部导航选项卡的活动,该活动选项卡正在更改其中的片段.当我在这些选项卡上来回单击时,它有时会停止工作.当我在其中添加一些日志时,代码执行得很好.但是片段没有被切换.

I have an activity with bottom navigation tabs that are changing the fragments in it. When I click back and forth on those tabs, at some point it stops working. Code executes just fine as I put some logs in it. But the fragments aren't being switched.

代码在kotlin中,但相当简单

Code is in kotlin but it's rather straight forward

fun showTabFragment(tag: String) {
        val currentFragment: Fragment? = supportFragmentManager.fragments?.lastOrNull()
        var fragment = supportFragmentManager.findFragmentByTag(tag)
        val fragmentExists = fragment != null
        if (fragment == null) {
            when (tag) {
                TAG_LOGBOOK -> fragment = LogbookFragment()
                TAG_RECIPES -> fragment = RecipesFragment()
                TAG_PROFILE -> fragment = ProfileFragment()
                else -> fragment = MeetingPlacesFragment()
            }
        }

        val transaction = supportFragmentManager.beginTransaction()

        if (currentFragment != null) {
            Log.i("jacek", "hiding " + currentFragment.javaClass.simpleName)
            transaction.hide(currentFragment)
        }

        if (fragmentExists) {
            Log.i("jacek", "showing " + fragment.javaClass.simpleName)
            transaction.show(fragment)
        } else {
            Log.i("jacek", "adding " + fragment.javaClass.simpleName)
            transaction.add(R.id.container, fragment, tag)
        }

        transaction.commit()
    }

碎片非常重.我会尝试一些轻量级的,但我认为这应该不成问题.还有什么我可以尝试的吗?

The fragments are quite heavy. I will try with some lightweight ones, but still that shouldn't be a problem in my opinion. Is there anything else I could try?

我正在使用最新的支持库-25.2.0 另外,我对替换片段不感兴趣,因为重点是添加交叉淡入淡出动画而无需重新创建它们

I'm using the latest support library - 25.2.0 Also I'm not interested in replacing the fragments as the point is to add crossfade animation without recreating them

推荐答案

您需要重用要隐藏或显示的片段的同一实例.

You need to reuse the same instance of a fragment that you wanted to hide or show.

private fun replaceFragment(fragment: Fragment) {
    supportFragmentManager.beginTransaction().apply {
        if (fragment.isAdded) {
            show(fragment)
        } else {
            add(R.id.fmFragmentContainer, fragment)
        }

        supportFragmentManager.fragments.forEach {
            if (it != fragment && it.isAdded) {
                hide(it)
            }
        }
    }.commit()
}

这篇关于FragmentTransaction隐藏/显示有时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆