如何通过Robolectric以编程方式获取自定义主题值

3

我可以通过以下方式在我的应用程序中访问自定义颜色主题值:

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;
1个回答

0
我们的团队在使用Robolectric时遇到了很大的问题,特别是某些类型的资源。似乎类型为和 的资源会抛出ResourceNotFound异常或返回不正确的值(如null或零)。根据您的项目设置,您可能可以使用Mockito来模拟主题,但除此之外我不知道还有什么可以做的 - 也许其他人会知道更多。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接