• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.util;
18 
19 import static androidx.lifecycle.Lifecycle.State.DESTROYED;
20 import static androidx.lifecycle.Lifecycle.State.RESUMED;
21 
22 import android.view.View;
23 import android.view.View.OnAttachStateChangeListener;
24 
25 import androidx.annotation.NonNull;
26 import androidx.lifecycle.Lifecycle;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LifecycleRegistry;
29 
30 /**
31  * Tools for generating lifecycle from sysui objects.
32  */
33 public class SysuiLifecycle {
34 
SysuiLifecycle()35     private SysuiLifecycle() {
36     }
37 
38     /**
39      * Get a lifecycle that will be put into the resumed state when the view is attached
40      * and goes to the destroyed state when the view is detached.
41      */
viewAttachLifecycle(View v)42     public static LifecycleOwner viewAttachLifecycle(View v) {
43         return new ViewLifecycle(v);
44     }
45 
46     private static class ViewLifecycle implements LifecycleOwner, OnAttachStateChangeListener {
47         private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this);
48 
ViewLifecycle(View v)49         ViewLifecycle(View v) {
50             v.addOnAttachStateChangeListener(this);
51             if (v.isAttachedToWindow()) {
52                 mLifecycle.markState(RESUMED);
53             }
54         }
55 
56         @NonNull
57         @Override
getLifecycle()58         public Lifecycle getLifecycle() {
59             return mLifecycle;
60         }
61 
62         @Override
onViewAttachedToWindow(View v)63         public void onViewAttachedToWindow(View v) {
64             mLifecycle.markState(RESUMED);
65         }
66 
67         @Override
onViewDetachedFromWindow(View v)68         public void onViewDetachedFromWindow(View v) {
69             mLifecycle.markState(DESTROYED);
70         }
71     }
72 }
73