1/*
2 * Copyright (C) 2017 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
17package com.android.setupwizardlib.template;
18
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.graphics.drawable.Drawable;
22import android.util.AttributeSet;
23import android.widget.ImageView;
24
25import com.android.setupwizardlib.R;
26import com.android.setupwizardlib.TemplateLayout;
27
28/**
29 * A {@link Mixin} for setting an icon on the template layout.
30 */
31public class IconMixin implements Mixin {
32
33    private TemplateLayout mTemplateLayout;
34
35    /**
36     * @param layout The template layout that this Mixin is a part of.
37     * @param attrs XML attributes given to the layout.
38     * @param defStyleAttr The default style attribute as given to the constructor of the layout.
39     */
40    public IconMixin(TemplateLayout layout, AttributeSet attrs, int defStyleAttr) {
41        mTemplateLayout = layout;
42        final Context context = layout.getContext();
43
44        final TypedArray a =
45                context.obtainStyledAttributes(attrs, R.styleable.SuwIconMixin, defStyleAttr, 0);
46
47        final Drawable icon = a.getDrawable(R.styleable.SuwIconMixin_android_icon);
48        if (icon != null) {
49            setIcon(icon);
50        }
51
52        a.recycle();
53    }
54
55    /**
56     * Sets the icon on this layout. The icon can also be set in XML using {@code android:icon}.
57     *
58     * @param icon A drawable icon.
59     */
60    public void setIcon(Drawable icon) {
61        final ImageView iconView = getView();
62        if (iconView != null) {
63            iconView.setImageDrawable(icon);
64        }
65    }
66
67    /**
68     * @return The icon previously set in {@link #setIcon(Drawable)} or {@code android:icon}
69     */
70    public Drawable getIcon() {
71        final ImageView iconView = getView();
72        return iconView != null ? iconView.getDrawable() : null;
73    }
74
75    /**
76     * @return The ImageView responsible for displaying the icon.
77     */
78    protected ImageView getView() {
79        return (ImageView) mTemplateLayout.findManagedViewById(R.id.suw_layout_icon);
80    }
81}
82