Java tutorial
//package com.java2s; import android.content.Context; import android.content.res.TypedArray; import android.util.Log; import android.util.SparseArray; public class Main { public static final boolean DEBUG = true; private static final String TAG = "Utilities"; private static final SparseArray<Integer> sColorAttrsArray = new SparseArray<>(); public static int getColorAttribute(Context context, int key, int defaultColor) { if (sColorAttrsArray.get(key) != null) { return sColorAttrsArray.get(key); } TypedArray a = null; try { int[] attr = new int[] { key }; int indexOfAttrBackgroundColor = 0; a = context.obtainStyledAttributes(attr); sColorAttrsArray.put(key, a.getColor(indexOfAttrBackgroundColor, defaultColor)); } catch (Exception e) { sColorAttrsArray.put(key, defaultColor); if (DEBUG) Log.w(TAG, "unexpected exception", e); } finally { if (a != null) a.recycle(); } return sColorAttrsArray.get(key); } }