1 /* 2 * Copyright (C) 2017 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 package com.android.settings.core; 15 16 import android.content.Context; 17 18 import androidx.preference.Preference; 19 import androidx.preference.TwoStatePreference; 20 21 import com.android.settings.slices.SliceData; 22 import com.android.settings.widget.MasterSwitchPreference; 23 24 /** 25 * Abstract class that consolidates logic for updating toggle controllers. 26 * It automatically handles the getting and setting of the switch UI element. 27 * Children of this class implement methods to get and set the underlying value of the setting. 28 */ 29 public abstract class TogglePreferenceController extends BasePreferenceController implements 30 Preference.OnPreferenceChangeListener { 31 32 private static final String TAG = "TogglePrefController"; 33 TogglePreferenceController(Context context, String preferenceKey)34 public TogglePreferenceController(Context context, String preferenceKey) { 35 super(context, preferenceKey); 36 } 37 38 /** 39 * @return {@code true} if the Setting is enabled. 40 */ isChecked()41 public abstract boolean isChecked(); 42 43 /** 44 * Set the Setting to {@param isChecked} 45 * 46 * @param isChecked Is {@code true} when the setting should be enabled. 47 * @return {@code true} if the underlying setting is updated. 48 */ setChecked(boolean isChecked)49 public abstract boolean setChecked(boolean isChecked); 50 51 @Override updateState(Preference preference)52 public void updateState(Preference preference) { 53 if (preference instanceof TwoStatePreference) { 54 ((TwoStatePreference) preference).setChecked(isChecked()); 55 } else if (preference instanceof MasterSwitchPreference) { 56 ((MasterSwitchPreference) preference).setChecked(isChecked()); 57 } else { 58 refreshSummary(preference); 59 } 60 } 61 62 @Override onPreferenceChange(Preference preference, Object newValue)63 public final boolean onPreferenceChange(Preference preference, Object newValue) { 64 return setChecked((boolean) newValue); 65 } 66 67 @Override 68 @SliceData.SliceType getSliceType()69 public int getSliceType() { 70 return SliceData.SliceType.SWITCH; 71 } 72 73 }