I got a method()
in the fragment. Fragment in host activity. So I need to call the method()
from fragment ONLY when host activity was in 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.
https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
You can, by SupportFragmentManager, get a Fragment by layout id, tag or name. But the most important thing here is in some situations Activity.onDestroy() method could never be called. So be careful if you implement code that needs to be executed, like an unsubscribe logic or removing callbacks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.