我可以通过以下方式在我的应用中访问自定义颜色主题值:
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;
}
但 Robolectric 在尝试访问 ColorStateList 时抛出 NPE。我注意到 mContext.getTheme() 返回一个带有 TypedArray 的主题,其数据为 0。
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;
最佳答案
在我目前的团队中,我们在获取某些类型的资源来与 Robolectric 合作时遇到了巨大的问题。看起来像资源类型,要么抛出 ResourceNotFound 异常,要么返回不正确的值(如 null 或零)。根据您的项目设置,您可以使用 Mockito 来模拟主题,但除此之外我不知道是否还有很多工作要做 - 也许其他人会知道更多。
关于android - 如何通过 Robolectric 以编程方式获取自定义主题值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26495123/