我可以通过以下方式在我的应用程序中访问自定义颜色主题值:
private int getTextColorFromTheme(int textAppearanceAttrResId, int state) {
TypedValue typedValue = new TypedValue();
>>>>/* missing TypedValue.data in Robolectric!! */
Resources.Theme theme = mContext.getTheme();
// textAppearanceAttrResId is a reference, so it is required to be retrieved this way.
theme.resolveAttribute(textAppearanceAttrResId, typedValue, true);
int[] textColorAttr = new int[]{android.R.attr.textColor};
int indexOfAttrTextColor = 0;
TypedArray a = mContext.obtainStyledAttributes(typedValue.data, textColorAttr);
ColorStateList csl = a.getColorStateList(indexOfAttrTextColor);
>>>>/* NPE thrown here in Robolectric! */
int color = csl.getColorForState(new int[]{state}, -1);
a.recycle();
return color;
}
但是当尝试访问ColorStateList时,Robolectric会抛出NPE异常。 我注意到mContext.getTheme()返回的主题具有数据为0的TypedArray。
mContext在setup()中先进行了设置:
ActivityController<MyActivity> activityController = Robolectric.buildActivity(MyActivity.class).attach();
MyActivity activity = activityController.get();
activity.setTheme(com.sudocoder.android.theme.R.style.Theme_Mine);
activityController.create().start().resume().visible();
mContext = activity;