1 /* 2 * Copyright (C) 2021 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.car.settings.common; 18 19 import android.content.Context; 20 import android.util.AttributeSet; 21 22 import androidx.annotation.Nullable; 23 import androidx.preference.Preference; 24 import androidx.preference.PreferenceViewHolder; 25 26 import com.android.car.ui.preference.CarUiPreference; 27 28 import java.util.function.Consumer; 29 30 /** 31 * Preference that can be given a disabled look but still be clickable. This enables behavior such 32 * as showing a Toast message when clicking on a disabled preference to explain why it's disabled. 33 */ 34 public class ClickableWhileDisabledPreference extends CarUiPreference { 35 36 private Consumer<Preference> mClickListener; 37 ClickableWhileDisabledPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)38 public ClickableWhileDisabledPreference(Context context, AttributeSet attrs, 39 int defStyleAttr, int defStyleRes) { 40 super(context, attrs, defStyleAttr, defStyleRes); 41 } 42 ClickableWhileDisabledPreference(Context context, AttributeSet attrs, int defStyleAttr)43 public ClickableWhileDisabledPreference(Context context, AttributeSet attrs, int defStyleAttr) { 44 super(context, attrs, defStyleAttr); 45 } 46 ClickableWhileDisabledPreference(Context context, AttributeSet attrs)47 public ClickableWhileDisabledPreference(Context context, AttributeSet attrs) { 48 super(context, attrs); 49 } 50 ClickableWhileDisabledPreference(Context context)51 public ClickableWhileDisabledPreference(Context context) { 52 super(context); 53 } 54 55 @Override onBindViewHolder(PreferenceViewHolder holder)56 public void onBindViewHolder(PreferenceViewHolder holder) { 57 super.onBindViewHolder(holder); 58 holder.itemView.setAllowClickWhenDisabled(true); 59 } 60 61 @Override 62 @SuppressWarnings("RestrictTo") performClick()63 public void performClick() { 64 if (!isEnabled()) { 65 if (mClickListener != null) { 66 mClickListener.accept(this); 67 } 68 } else { 69 super.performClick(); 70 } 71 } 72 73 /** 74 * Sets the click listener for when the preference is disabled. 75 * @param listener Listener to call when the preference is disabled and clicked. 76 */ setDisabledClickListener(@ullable Consumer<Preference> listener)77 public void setDisabledClickListener(@Nullable Consumer<Preference> listener) { 78 mClickListener = listener; 79 } 80 } 81