Rade
Rade

Reputation: 320

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();
    }
}

Upvotes: 0

Views: 2815

Answers (1)

eXact
eXact

Reputation: 61

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)

Upvotes: 1

Related Questions