1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5  * except in compliance with the License. You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the
10  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11  * KIND, either express or implied. See the License for the specific language governing
12  * permissions and limitations under the License.
13  */
14 
15 package com.android.systemui.fragments;
16 
17 import android.app.Fragment;
18 import android.util.Log;
19 import android.view.View;
20 
21 import com.android.systemui.plugins.FragmentBase;
22 import com.android.systemui.statusbar.policy.ExtensionController.Extension;
23 
24 import java.util.function.Consumer;
25 
26 /**
27  * Wires up an Extension to a Fragment tag/id so that it always contains the class
28  * selected by the extension.
29  */
30 public class ExtensionFragmentListener<T extends FragmentBase> implements Consumer<T> {
31 
32     private static final String TAG = "ExtensionFragmentListener";
33 
34     private final FragmentHostManager mFragmentHostManager;
35     private final String mTag;
36     private final Extension<T> mExtension;
37     private final int mId;
38     private String mOldClass;
39 
ExtensionFragmentListener(View view, String tag, int id, Extension<T> extension)40     private ExtensionFragmentListener(View view, String tag, int id, Extension<T> extension) {
41         mTag = tag;
42         mFragmentHostManager = FragmentHostManager.get(view);
43         mExtension = extension;
44         mId = id;
45         mFragmentHostManager.getFragmentManager().beginTransaction()
46                 .replace(id, (Fragment) mExtension.get(), mTag)
47                 .commit();
48         mExtension.clearItem(false);
49     }
50 
51     @Override
accept(T extension)52     public void accept(T extension) {
53         try {
54             Fragment.class.cast(extension);
55             mFragmentHostManager.getExtensionManager().setCurrentExtension(mId, mTag,
56                     mOldClass, extension.getClass().getName(), mExtension.getContext());
57             mOldClass = extension.getClass().getName();
58         } catch (ClassCastException e) {
59             Log.e(TAG, extension.getClass().getName() + " must be a Fragment", e);
60         }
61         mExtension.clearItem(true);
62     }
63 
attachExtensonToFragment(View view, String tag, int id, Extension<T> extension)64     public static <T> void attachExtensonToFragment(View view, String tag, int id,
65             Extension<T> extension) {
66         extension.addCallback(new ExtensionFragmentListener(view, tag, id, extension));
67     }
68 }
69