android-fragments 如何在Kotlin摧毁断片?

0h4hbjxa  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(150)

我试图在使用getFragmentManager()?.beginTransaction()?.remove(MyFragment)?.commitAllowingStateLoss()切换到同一个activity上的另一个fragment时销毁以前的fragment,但在remove()部分,我把我的片段的名称放在那里,它说**必需:碎片!找到:* * 我想这是因为我在这个fragment中使用了伴随对象,因为我需要它来实现putExtra函数。**如何销毁片段,即使其中有一个伴随对象?**谢谢。

vnzz0bqm

vnzz0bqm1#

remove()接受一个 *Fragment示例 *,您只需将 *Fragment类 * 的名称传递给它即可。

class MyFragment : Fragment()

// Not this
remove(MyFragment)

// You have to get a reference to the Fragment object
// Either use the ID of a Fragment added in XML, or the ID of the container you
// added it to in a FragmentTransaction
val actualFragment =  fragmentManager.findFragmentById(R.id.that_id)
// Or use a Tag you added in XML or through a transaction
val actualFragment = fragmentManager.findFragmentByTag("some tag")

// now you have the Fragment, you can remove it
remove(actualFragment)

因为在Kotlin中,你可以将MyFragment.Companion.someProperty缩写为MyFragment.someProperty,仅仅使用MyFragment作为一个值(就像你在这里所做的--remove需要一个 object)就意味着你实际上引用了MyFragment.Companion。所以你在这里有一个伴随对象并不是问题所在,你只是做了一件错误的事情,试图将它传递给remove

相关问题