AppCompatImageHelper.java revision 7e4e8b664820f773bc96e37ee1d2bbf500d64e69
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.support.v4.content.ContextCompat;
20import android.support.v7.internal.widget.AppCompatDrawableManager;
21import android.support.v7.internal.widget.TintTypedArray;
22import android.util.AttributeSet;
23import android.widget.ImageView;
24
25class AppCompatImageHelper {
26
27    private static final int[] VIEW_ATTRS = {android.R.attr.src};
28
29    private final ImageView mView;
30    private final AppCompatDrawableManager mDrawableManager;
31
32    AppCompatImageHelper(ImageView view, AppCompatDrawableManager drawableManager) {
33        mView = view;
34        mDrawableManager = drawableManager;
35    }
36
37    void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {
38        TintTypedArray a = TintTypedArray.obtainStyledAttributes(mView.getContext(), attrs,
39                VIEW_ATTRS, defStyleAttr, 0);
40        try {
41            if (a.hasValue(0)) {
42                mView.setImageDrawable(a.getDrawable(0));
43            }
44        } finally {
45            a.recycle();
46        }
47    }
48
49    void setImageResource(int resId) {
50        mView.setImageDrawable(mDrawableManager != null
51                ? mDrawableManager.getDrawable(mView.getContext(), resId)
52                : ContextCompat.getDrawable(mView.getContext(), resId));
53    }
54}
55