Jason Monk | 8e4e4cb | 2018-12-04 11:10:24 -0500 | [diff] [blame] | 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 | |
| 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 | */ |
| 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 | |
| 49 | ViewLifecycle(View v) { |
| 50 | v.addOnAttachStateChangeListener(this); |
| 51 | } |
| 52 | |
| 53 | @NonNull |
| 54 | @Override |
| 55 | public Lifecycle getLifecycle() { |
| 56 | return mLifecycle; |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public void onViewAttachedToWindow(View v) { |
| 61 | mLifecycle.markState(RESUMED); |
| 62 | } |
| 63 | |
| 64 | @Override |
| 65 | public void onViewDetachedFromWindow(View v) { |
| 66 | mLifecycle.markState(DESTROYED); |
| 67 | } |
| 68 | } |
| 69 | } |