1 /* 2 * Copyright (C) 2023 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.permissioncontroller.role.ui; 18 19 import android.content.Intent; 20 21 import androidx.annotation.NonNull; 22 import androidx.annotation.Nullable; 23 import androidx.preference.Preference; 24 import androidx.preference.PreferenceViewHolder; 25 26 /** 27 * Mixin for implementing {@link RestrictionAwarePreference}. 28 */ 29 public class RestrictionAwarePreferenceMixin { 30 31 private static final String LOG_TAG = RestrictionAwarePreferenceMixin.class.getSimpleName(); 32 33 @NonNull 34 private final Preference mPreference; 35 36 @Nullable 37 private Intent mRestrictionIntent; 38 RestrictionAwarePreferenceMixin(@onNull Preference preference)39 public RestrictionAwarePreferenceMixin(@NonNull Preference preference) { 40 mPreference = preference; 41 } 42 43 /** 44 * Implementation for {@link RestrictionAwarePreference#setRestrictionIntent}. 45 */ setRestrictionIntent(@ullable Intent restrictionIntent)46 public void setRestrictionIntent(@Nullable Intent restrictionIntent) { 47 mRestrictionIntent = restrictionIntent; 48 mPreference.setEnabled(mRestrictionIntent == null); 49 } 50 51 /** 52 * Call after {@link Preference#onBindViewHolder} to apply blocking effects. 53 */ onAfterBindViewHolder(@onNull PreferenceViewHolder holder)54 public void onAfterBindViewHolder(@NonNull PreferenceViewHolder holder) { 55 if (mRestrictionIntent != null) { 56 // We set the item view to enabled to make the preference row clickable. 57 // Normal disabled preferences have the whole view hierarchy disabled, so by making only 58 // the top-level itemView enabled, we don't change the fact that the whole preference 59 // still "looks" disabled (see Preference.onBindViewHolder). 60 // Preference.onBindViewHolder sets the onClickListener as well on each preference, so 61 // we don't need to unset the listener here (we wouldn't know the correct one anyway). 62 // This approach is used already by com.android.settingslib.RestrictedPreferenceHelper. 63 holder.itemView.setEnabled(true); 64 holder.itemView.setOnClickListener( 65 view -> view.getContext().startActivity(mRestrictionIntent)); 66 } 67 } 68 } 69