简体   繁体   English

Custom View是否接收Activity / Fragment生命周期回调?

[英]Custom View receives Activity/Fragment lifecycle callbacks?

I'm working on custom view that will be used as normal android view component. 我正在研究将用作普通android视图组件的自定义视图。 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: 我的目标是避免最终用户(dev)覆盖每个生命周期回调,以便将状态与我的视图同步,例如:

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

If you are using Architecture Components you can implement LifecycleObserver interface, then: 如果使用的是体系结构组件 ,则可以实现LifecycleObserver接口,然后:

  1. Annotate your view's onStop() method with @OnLifecycleEvent(Lifecycle.Event.ON_STOP) 使用@OnLifecycleEvent(Lifecycle.Event.ON_STOP)注释视图的onStop()方法
  2. In view's constructor register the observer: ((LifecycleOwner)context).getLifecycle().addObserver(this) 在视图的构造函数中注册观察者: ((LifecycleOwner)context).getLifecycle().addObserver(this)

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

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