AppCompatImageHelper.java revision aaa85b7d563d27fdf10048dd619a317451477ad5
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
17package android.support.v7.widget;
18
19import android.graphics.drawable.Drawable;
20import android.support.v4.content.ContextCompat;
21import android.support.v7.appcompat.R;
22import android.util.AttributeSet;
23import android.widget.ImageView;
24
25class AppCompatImageHelper {
26
27    private final ImageView mView;
28    private final AppCompatDrawableManager mDrawableManager;
29
30    AppCompatImageHelper(ImageView view, AppCompatDrawableManager drawableManager) {
31        mView = view;
32        mDrawableManager = drawableManager;
33    }
34
35    void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {
36        TintTypedArray a = TintTypedArray.obtainStyledAttributes(mView.getContext(), attrs,
37                R.styleable.AppCompatImageView, defStyleAttr, 0);
38        try {
39            Drawable d = a.getDrawableIfKnown(R.styleable.AppCompatImageView_android_src);
40            if (d != null) {
41                mView.setImageDrawable(d);
42            }
43
44            final int id = a.getResourceId(R.styleable.AppCompatImageView_srcCompat, -1);
45            if (id != -1) {
46                d = mDrawableManager.getDrawable(mView.getContext(), id);
47                if (d != null) {
48                    mView.setImageDrawable(d);
49                }
50            }
51
52            final Drawable drawable = mView.getDrawable();
53            if (drawable != null) {
54                DrawableUtils.fixDrawable(drawable);
55            }
56        } finally {
57            a.recycle();
58        }
59    }
60
61    void setImageResource(int resId) {
62        if (resId != 0) {
63            final Drawable d = mDrawableManager != null
64                    ? mDrawableManager.getDrawable(mView.getContext(), resId)
65                    : ContextCompat.getDrawable(mView.getContext(), resId);
66            if (d != null) {
67                DrawableUtils.fixDrawable(d);
68            }
69            mView.setImageDrawable(d);
70        } else {
71            mView.setImageDrawable(null);
72        }
73    }
74}
75