1 /* 2 * Copyright (C) 2017 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.settings.core; 18 19 import android.content.Context; 20 import android.support.v7.preference.Preference; 21 import android.support.v7.preference.PreferenceScreen; 22 23 import com.android.settingslib.core.AbstractPreferenceController; 24 import com.android.settingslib.core.lifecycle.Lifecycle; 25 import com.android.settingslib.core.lifecycle.LifecycleObserver; 26 import com.android.settingslib.core.lifecycle.events.OnResume; 27 28 public abstract class DynamicAvailabilityPreferenceController extends AbstractPreferenceController 29 implements PreferenceControllerMixin, LifecycleObserver, OnResume { 30 31 private Preference mPreference; 32 private PreferenceScreen mScreen; 33 private PreferenceAvailabilityObserver mAvailabilityObserver = null; 34 35 public DynamicAvailabilityPreferenceController(Context context, Lifecycle lifecycle) { 36 super(context); 37 if (lifecycle != null) { 38 lifecycle.addObserver(this); 39 } 40 } 41 42 public void setAvailabilityObserver(PreferenceAvailabilityObserver observer) { 43 mAvailabilityObserver = observer; 44 } 45 46 public PreferenceAvailabilityObserver getAvailabilityObserver() { 47 return mAvailabilityObserver; 48 } 49 50 @Override 51 public void displayPreference(PreferenceScreen screen) { 52 mScreen = screen; 53 mPreference = screen.findPreference(getPreferenceKey()); 54 super.displayPreference(screen); 55 } 56 57 @Override 58 public void onResume() { 59 if (!isAvailable()) { 60 removePreference(mScreen, getPreferenceKey()); 61 return; 62 } 63 64 updateState(mPreference); 65 if (mScreen.findPreference(getPreferenceKey()) == null) { 66 mScreen.addPreference(mPreference); 67 } 68 } 69 70 protected void notifyOnAvailabilityUpdate(boolean available) { 71 if (mAvailabilityObserver != null) { 72 mAvailabilityObserver.onPreferenceAvailabilityUpdated(getPreferenceKey(), available); 73 } 74 } 75 } 76