title: How to make custom view observe containing fragment's lifecycle events instead of activity?
body: <p>I have an activity and several fragments that it replaces inside a frame layout. Each fragment contains a layout inflated from XML with a number of custom views. Inside those views, I want to subscribe to lifecycle events in these views using LifecycleObserver. My view in Kotlin:</p>
  
  <pre><code>class MyView(context: Context) : View(context, null, 0): LifecycleObserver {
  
      init {
          (getContext() as LifecycleOwner).lifecycle.addObserver(this)
      }
  
      @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
      fun onResume() {
          // code
      }
  
      @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
      fun onPause() {
          // code
      }
  
      @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
      fun onDestroy() {
          lifecycle.removeObserver(this)
      }
  
  }
  </code></pre>
  
  <p>The problem is, when one fragment goes away and is replaced by another, the views in the first fragment don't receive an <strong>onPause</strong> event. Nor do they get <strong>onResume</strong> when I return to it from the second fragment. The views receive <strong>onPause</strong> only when the whole <strong>activity</strong> is paused, but they are unaware of lifecycle changes in the <strong>fragments</strong>. I tracked this down to layout inflater, that is used to inflate fragment's xml layout, it passes the activity as <strong>context</strong> parameter to views. This is how layout inflater is instantiated in support library's Fragment class:</p>
  
  <pre><code>/** @deprecated */
  @Deprecated
  @NonNull
  @RestrictTo({Scope.LIBRARY_GROUP})
  public LayoutInflater getLayoutInflater(@Nullable Bundle savedFragmentState) {
      if (this.mHost == null) {
          throw new IllegalStateException("onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager.");
      } else {
          LayoutInflater result = this.mHost.onGetLayoutInflater();
          this.getChildFragmentManager();
          LayoutInflaterCompat.setFactory2(result, this.mChildFragmentManager.getLayoutInflaterFactory());
          return result;
      }
  }
  </code></pre>
  
  <p>The <strong>mHost</strong> is a FragmentActivity that contains this fragment. Hence, LayoutInflater that's passed into fragment's onCreateView() contains a reference to the FragmentActivity as a context. So the views effectively observe Activity lifecycle.</p>
  
  <p>How do I make my custom views observe lifecycle events of their containing fragment?</p>