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