1 /* 2 * Copyright (C) 2014 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 android.preference; 18 19 import com.android.ide.common.rendering.api.ILayoutLog; 20 import com.android.layoutlib.bridge.android.BridgeContext; 21 import com.android.layoutlib.bridge.android.BridgeXmlBlockParser; 22 23 import android.content.Context; 24 import android.util.AttributeSet; 25 import android.view.InflateException; 26 27 import static com.android.layoutlib.bridge.Bridge.getLog; 28 29 public class BridgePreferenceInflater extends PreferenceInflater { 30 BridgePreferenceInflater(Context context, PreferenceManager preferenceManager)31 public BridgePreferenceInflater(Context context, PreferenceManager preferenceManager) { 32 super(context, preferenceManager); 33 } 34 35 @Override createItem(String name, String prefix, AttributeSet attrs)36 public Preference createItem(String name, String prefix, AttributeSet attrs) 37 throws ClassNotFoundException { 38 Object viewKey = null; 39 BridgeContext bc = null; 40 41 Context context = getContext(); 42 if (context instanceof BridgeContext) { 43 bc = (BridgeContext) context; 44 } 45 46 if (attrs instanceof BridgeXmlBlockParser) { 47 viewKey = ((BridgeXmlBlockParser) attrs).getViewCookie(); 48 } 49 50 Preference preference = null; 51 try { 52 preference = super.createItem(name, prefix, attrs); 53 } catch (ClassNotFoundException | InflateException exception) { 54 // name is probably not a valid preference type 55 if (("android.support.v7.preference".equals(prefix) || 56 "androidx.preference".equals(prefix)) && 57 "SwitchPreferenceCompat".equals(name)) { 58 preference = super.createItem("SwitchPreference", prefix, attrs); 59 } else { 60 // Log the error and rethrow the exception as returning null would later result in 61 // a NullPointerException without a good error message for the user. 62 getLog().error(ILayoutLog.TAG_INFLATE, exception.getMessage(), null, null); 63 throw exception; 64 } 65 } 66 67 if (viewKey != null && bc != null) { 68 bc.addCookie(preference, viewKey); 69 } 70 return preference; 71 } 72 } 73