简体   繁体   English

仅当主机活动被破坏时如何从片段调用方法?

[英]How to call method from fragment only if host activity was destroyed?

I got a method() in the fragment.我在片段中有一个method() Fragment in host activity.宿主活动中的片段。 So I need to call the method() from fragment ONLY when host activity was in onDestroy() .因此,仅当主机活动处于onDestroy()时,我才需要从片段中调用method() onDestroy() Maybe it suppose to be something like a static flag?也许它应该像一个静态标志?

class MyActivity:  AppCompatActivity() {
    override fun onDestroy() {
        super.onDestroy()
        val fragment = supportFragmentManager.findFragmentById(R.id.my_fragment) as MyFragment
        if (fragment != null) {
            fragment.myMethod()
        }
    }
}
class MyFragment: Fragment() {
    fun myMethod() {
    }
}

Or use a ViewModel to handle communication between the activity and the fragment.或者使用 ViewModel 来处理活动和片段之间的通信。

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

You can, by SupportFragmentManager, get a Fragment by layout id, tag or name.您可以通过 SupportFragmentManager,通过布局 ID、标签或名称获取 Fragment。 But the most important thing here is in some situations Activity.onDestroy() method could never be called.但这里最重要的是在某些情况下 Activity.onDestroy() 方法永远不会被调用。 So be careful if you implement code that needs to be executed, like an unsubscribe logic or removing callbacks.因此,如果您实现需要执行的代码(例如取消订阅逻辑或删除回调),请务必小心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM