1/*
2 * Copyright (C) 2016 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
17package com.android.settingslib.widget;
18
19import android.content.Context;
20import android.support.v14.preference.PreferenceFragment;
21import android.support.v7.preference.PreferenceScreen;
22
23import com.android.settingslib.core.lifecycle.Lifecycle;
24import com.android.settingslib.core.lifecycle.LifecycleObserver;
25import com.android.settingslib.core.lifecycle.events.SetPreferenceScreen;
26
27public class FooterPreferenceMixin implements LifecycleObserver, SetPreferenceScreen {
28
29    private final PreferenceFragment mFragment;
30    private FooterPreference mFooterPreference;
31
32    public FooterPreferenceMixin(PreferenceFragment fragment, Lifecycle lifecycle) {
33        mFragment = fragment;
34        lifecycle.addObserver(this);
35    }
36
37    @Override
38    public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
39        if (mFooterPreference != null) {
40            preferenceScreen.addPreference(mFooterPreference);
41        }
42    }
43
44    /**
45     * Creates a new {@link FooterPreference}.
46     */
47    public FooterPreference createFooterPreference() {
48        final PreferenceScreen screen = mFragment.getPreferenceScreen();
49        if (mFooterPreference != null && screen != null) {
50            screen.removePreference(mFooterPreference);
51        }
52        mFooterPreference = new FooterPreference(getPrefContext());
53
54        if (screen != null) {
55            screen.addPreference(mFooterPreference);
56        }
57        return mFooterPreference;
58    }
59
60    /**
61     * Returns an UI context with theme properly set for new Preference objects.
62     */
63    private Context getPrefContext() {
64        return mFragment.getPreferenceManager().getContext();
65    }
66
67    public boolean hasFooter() {
68        return mFooterPreference != null;
69    }
70}
71
72