AppCompatImageHelper.java revision 66698bb15ba0f873aa1c2290cc50d6bb839a474a
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.util.AttributeSet;
21import android.widget.ImageView;
22
23class AppCompatImageHelper {
24
25    private static final int[] VIEW_ATTRS = {android.R.attr.src};
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                VIEW_ATTRS, defStyleAttr, 0);
38        try {
39            if (a.hasValue(0)) {
40                mView.setImageDrawable(a.getDrawable(0));
41            }
42        } finally {
43            a.recycle();
44        }
45    }
46
47    void setImageResource(int resId) {
48        if (resId != 0) {
49            mView.setImageDrawable(mDrawableManager != null
50                    ? mDrawableManager.getDrawable(mView.getContext(), resId)
51                    : ContextCompat.getDrawable(mView.getContext(), resId));
52        } else {
53            mView.setImageDrawable(null);
54        }
55    }
56}
57