Skip to content

Commit 32ebe06

Browse files
committed
[Refactor] A better way of fixing getColorFromAttrRes().
1 parent 37ff30f commit 32ebe06

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

  • library/src/main/java/me/zhanghai/android/fastscroll

library/src/main/java/me/zhanghai/android/fastscroll/Utils.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,33 +17,36 @@
1717
package me.zhanghai.android.fastscroll;
1818

1919
import android.content.Context;
20+
import android.content.res.ColorStateList;
2021
import android.content.res.TypedArray;
21-
import android.util.DisplayMetrics;
22-
import android.util.TypedValue;
2322

2423
import androidx.annotation.AttrRes;
2524
import androidx.annotation.ColorInt;
2625
import androidx.annotation.NonNull;
26+
import androidx.annotation.Nullable;
2727
import androidx.appcompat.content.res.AppCompatResources;
2828

2929
class Utils {
3030

3131
@ColorInt
3232
public static int getColorFromAttrRes(@AttrRes int attrRes, @NonNull Context context) {
33+
ColorStateList colorStateList = getColorStateListFromAttrRes(attrRes, context);
34+
return colorStateList != null ? colorStateList.getDefaultColor() : 0;
35+
}
36+
37+
@Nullable
38+
public static ColorStateList getColorStateListFromAttrRes(@AttrRes int attrRes,
39+
@NonNull Context context) {
3340
TypedArray a = context.obtainStyledAttributes(new int[] { attrRes });
34-
int type = a.getType(0);
35-
if (type >= TypedValue.TYPE_FIRST_INT && type <= TypedValue.TYPE_LAST_INT) {
36-
return a.getColor(0, 0);
37-
}
3841
int resId;
3942
try {
4043
resId = a.getResourceId(0, 0);
44+
if (resId != 0) {
45+
return AppCompatResources.getColorStateList(context, resId);
46+
}
47+
return a.getColorStateList(0);
4148
} finally {
4249
a.recycle();
4350
}
44-
if (resId == 0) {
45-
return 0;
46-
}
47-
return AppCompatResources.getColorStateList(context, resId).getDefaultColor();
4851
}
4952
}

0 commit comments

Comments
 (0)