簡體   English   中英

如何銷毀 kotlin 中的片段?

[英]How to destroy fragment in kotlin?

我試圖通過使用 getFragmentManager()?.beginTransaction()?.remove(MyFragment)?.commitAllowingStateLoss() 切換到同一活動上的另一個片段時破壞以前的片段,但在 remove() 部分,我把片段的名稱,它說“必需:片段:找到。MyFragment.Companion”我認為這是因為我在這個片段中使用了伴侶 object,因為我需要它用於 putExtra function? 即使其中有伴隨的 object 如何銷毀片段。 謝謝。

remove()需要一個Fragment 實例,您只是將Fragment class的名稱傳遞給它。

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 所以事實上你有一個伴侶 object 這里不是問題,你只是在做錯事,試圖將它傳遞給remove

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM