1 /* 2 * Copyright (C) 2015 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.setupwizardlib; 18 19 import android.annotation.TargetApi; 20 import android.content.Context; 21 import android.content.res.TypedArray; 22 import android.os.Build.VERSION_CODES; 23 import androidx.annotation.Keep; 24 import androidx.annotation.LayoutRes; 25 import androidx.annotation.StyleRes; 26 import android.util.AttributeSet; 27 import android.view.LayoutInflater; 28 import android.view.View; 29 import android.view.ViewGroup; 30 import android.view.ViewTreeObserver; 31 import android.widget.FrameLayout; 32 import com.android.setupwizardlib.template.Mixin; 33 import com.android.setupwizardlib.util.FallbackThemeWrapper; 34 import java.util.HashMap; 35 import java.util.Map; 36 37 /** 38 * A generic template class that inflates a template, provided in the constructor or in {@code 39 * android:layout} through XML, and adds its children to a "container" in the template. When 40 * inflating this layout from XML, the {@code android:layout} and {@code suwContainer} attributes 41 * are required. 42 */ 43 public class TemplateLayout extends FrameLayout { 44 45 /** 46 * The container of the actual content. This will be a view in the template, which child views 47 * will be added to when {@link #addView(View)} is called. 48 */ 49 private ViewGroup container; 50 51 private final Map<Class<? extends Mixin>, Mixin> mixins = new HashMap<>(); 52 TemplateLayout(Context context, int template, int containerId)53 public TemplateLayout(Context context, int template, int containerId) { 54 super(context); 55 init(template, containerId, null, R.attr.suwLayoutTheme); 56 } 57 TemplateLayout(Context context, AttributeSet attrs)58 public TemplateLayout(Context context, AttributeSet attrs) { 59 super(context, attrs); 60 init(0, 0, attrs, R.attr.suwLayoutTheme); 61 } 62 63 @TargetApi(VERSION_CODES.HONEYCOMB) TemplateLayout(Context context, AttributeSet attrs, int defStyleAttr)64 public TemplateLayout(Context context, AttributeSet attrs, int defStyleAttr) { 65 super(context, attrs, defStyleAttr); 66 init(0, 0, attrs, defStyleAttr); 67 } 68 69 // All the constructors delegate to this init method. The 3-argument constructor is not 70 // available in LinearLayout before v11, so call super with the exact same arguments. init(int template, int containerId, AttributeSet attrs, int defStyleAttr)71 private void init(int template, int containerId, AttributeSet attrs, int defStyleAttr) { 72 final TypedArray a = 73 getContext().obtainStyledAttributes(attrs, R.styleable.SuwTemplateLayout, defStyleAttr, 0); 74 if (template == 0) { 75 template = a.getResourceId(R.styleable.SuwTemplateLayout_android_layout, 0); 76 } 77 if (containerId == 0) { 78 containerId = a.getResourceId(R.styleable.SuwTemplateLayout_suwContainer, 0); 79 } 80 inflateTemplate(template, containerId); 81 82 a.recycle(); 83 } 84 85 /** 86 * Registers a mixin with a given class. This method should be called in the constructor. 87 * 88 * @param cls The class to register the mixin. In most cases, {@code cls} is the same as {@code 89 * mixin.getClass()}, but {@code cls} can also be a super class of that. In the latter case 90 * the mixin must be retrieved using {@code cls} in {@link #getMixin(Class)}, not the 91 * subclass. 92 * @param mixin The mixin to be registered. 93 * @param <M> The class of the mixin to register. This is the same as {@code cls} 94 */ registerMixin(Class<M> cls, M mixin)95 protected <M extends Mixin> void registerMixin(Class<M> cls, M mixin) { 96 mixins.put(cls, mixin); 97 } 98 99 /** 100 * Same as {@link android.view.View#findViewById(int)}, but may include views that are managed by 101 * this view but not currently added to the view hierarchy. e.g. recycler view or list view 102 * headers that are not currently shown. 103 */ 104 // Returning generic type is the common pattern used for findViewBy* methods 105 @SuppressWarnings("TypeParameterUnusedInFormals") findManagedViewById(int id)106 public <T extends View> T findManagedViewById(int id) { 107 return findViewById(id); 108 } 109 110 /** 111 * Get a {@link Mixin} from this template registered earlier in {@link #registerMixin(Class, 112 * Mixin)}. 113 * 114 * @param cls The class marker of Mixin being requested. The actual Mixin returned may be a 115 * subclass of this marker. Note that this must be the same class as registered in {@link 116 * #registerMixin(Class, Mixin)}, which is not necessarily the same as the concrete class of 117 * the instance returned by this method. 118 * @param <M> The type of the class marker. 119 * @return The mixin marked by {@code cls}, or null if the template does not have a matching 120 * mixin. 121 */ 122 @SuppressWarnings("unchecked") getMixin(Class<M> cls)123 public <M extends Mixin> M getMixin(Class<M> cls) { 124 return (M) mixins.get(cls); 125 } 126 127 @Override addView(View child, int index, ViewGroup.LayoutParams params)128 public void addView(View child, int index, ViewGroup.LayoutParams params) { 129 container.addView(child, index, params); 130 } 131 addViewInternal(View child)132 private void addViewInternal(View child) { 133 super.addView(child, -1, generateDefaultLayoutParams()); 134 } 135 inflateTemplate(int templateResource, int containerId)136 private void inflateTemplate(int templateResource, int containerId) { 137 final LayoutInflater inflater = LayoutInflater.from(getContext()); 138 final View templateRoot = onInflateTemplate(inflater, templateResource); 139 addViewInternal(templateRoot); 140 141 container = findContainer(containerId); 142 if (container == null) { 143 throw new IllegalArgumentException("Container cannot be null in TemplateLayout"); 144 } 145 onTemplateInflated(); 146 } 147 148 /** 149 * Inflate the template using the given inflater and theme. The fallback theme will be applied to 150 * the theme without overriding the values already defined in the theme, but simply providing 151 * default values for values which have not been defined. This allows templates to add additional 152 * required theme attributes without breaking existing clients. 153 * 154 * <p>In general, clients should still set the activity theme to the corresponding theme in setup 155 * wizard lib, so that the content area gets the correct styles as well. 156 * 157 * @param inflater A LayoutInflater to inflate the template. 158 * @param fallbackTheme A fallback theme to apply to the template. If the values defined in the 159 * fallback theme is already defined in the original theme, the value in the original theme 160 * takes precedence. 161 * @param template The layout template to be inflated. 162 * @return Root of the inflated layout. 163 * @see FallbackThemeWrapper 164 */ inflateTemplate( LayoutInflater inflater, @StyleRes int fallbackTheme, @LayoutRes int template)165 protected final View inflateTemplate( 166 LayoutInflater inflater, @StyleRes int fallbackTheme, @LayoutRes int template) { 167 if (template == 0) { 168 throw new IllegalArgumentException("android:layout not specified for TemplateLayout"); 169 } 170 if (fallbackTheme != 0) { 171 inflater = 172 LayoutInflater.from(new FallbackThemeWrapper(inflater.getContext(), fallbackTheme)); 173 } 174 return inflater.inflate(template, this, false); 175 } 176 177 /** 178 * This method inflates the template. Subclasses can override this method to customize the 179 * template inflation, or change to a different default template. The root of the inflated layout 180 * should be returned, and not added to the view hierarchy. 181 * 182 * @param inflater A LayoutInflater to inflate the template. 183 * @param template The resource ID of the template to be inflated, or 0 if no template is 184 * specified. 185 * @return Root of the inflated layout. 186 */ onInflateTemplate(LayoutInflater inflater, @LayoutRes int template)187 protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) { 188 return inflateTemplate(inflater, 0, template); 189 } 190 findContainer(int containerId)191 protected ViewGroup findContainer(int containerId) { 192 if (containerId == 0) { 193 // Maintain compatibility with the deprecated way of specifying container ID. 194 containerId = getContainerId(); 195 } 196 return (ViewGroup) findViewById(containerId); 197 } 198 199 /** 200 * This is called after the template has been inflated and added to the view hierarchy. Subclasses 201 * can implement this method to modify the template as necessary, such as caching views retrieved 202 * from findViewById, or other view operations that need to be done in code. You can think of this 203 * as {@link View#onFinishInflate()} but for inflation of the template instead of for child views. 204 */ onTemplateInflated()205 protected void onTemplateInflated() {} 206 207 /** 208 * @return ID of the default container for this layout. This will be used to find the container 209 * ViewGroup, which all children views of this layout will be placed in. 210 * @deprecated Override {@link #findContainer(int)} instead. 211 */ 212 @Deprecated getContainerId()213 protected int getContainerId() { 214 return 0; 215 } 216 217 /* Animator support */ 218 219 private float xFraction; 220 private ViewTreeObserver.OnPreDrawListener preDrawListener; 221 222 /** 223 * Set the X translation as a fraction of the width of this view. Make sure this method is not 224 * stripped out by proguard when using this with {@link android.animation.ObjectAnimator}. You may 225 * need to add <code> 226 * -keep @androidx.annotation.Keep class * 227 * </code> to your proguard configuration if you are seeing mysterious {@link NoSuchMethodError} 228 * at runtime. 229 */ 230 @Keep 231 @TargetApi(VERSION_CODES.HONEYCOMB) setXFraction(float fraction)232 public void setXFraction(float fraction) { 233 xFraction = fraction; 234 final int width = getWidth(); 235 if (width != 0) { 236 setTranslationX(width * fraction); 237 } else { 238 // If we haven't done a layout pass yet, wait for one and then set the fraction before 239 // the draw occurs using an OnPreDrawListener. Don't call translationX until we know 240 // getWidth() has a reliable, non-zero value or else we will see the fragment flicker on 241 // screen. 242 if (preDrawListener == null) { 243 preDrawListener = 244 new ViewTreeObserver.OnPreDrawListener() { 245 @Override 246 public boolean onPreDraw() { 247 getViewTreeObserver().removeOnPreDrawListener(preDrawListener); 248 setXFraction(xFraction); 249 return true; 250 } 251 }; 252 getViewTreeObserver().addOnPreDrawListener(preDrawListener); 253 } 254 } 255 } 256 257 /** 258 * Return the X translation as a fraction of the width, as previously set in {@link 259 * #setXFraction(float)}. 260 * 261 * @see #setXFraction(float) 262 */ 263 @Keep 264 @TargetApi(VERSION_CODES.HONEYCOMB) getXFraction()265 public float getXFraction() { 266 return xFraction; 267 } 268 } 269