简体   繁体   中英

Custom View receives Activity/Fragment lifecycle callbacks?

I'm working on custom view that will be used as normal android view component. Is it possible to internally handle hosts (activity/fragment) lifecycle states?

My goal is to avoid end users (devs) to override every lifecycle callback in order to sync states with my view, for example:

@Override
protected void onStop() {
    super.onStop();
    if (myCustomView != null) {
        myCustomView.onStop();
    }
}

If you are using Architecture Components you can implement LifecycleObserver interface, then:

  1. Annotate your view's onStop() method with @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  2. In view's constructor register the observer: ((LifecycleOwner)context).getLifecycle().addObserver(this)

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.

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