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

标签 android android-theme robolectric

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

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/

相关文章:

android - android studio 中带有 firebase 的 Google 登录按钮,错误 : cannot find symbol variable default_web_client_id

java - <anonymous> 不是抽象的,不会覆盖 AsyncHttpResponseHandler 中的抽象方法 onFailure(int,Header[],byte[],Throwable)

具有不同基本主题的 Android 风格

java - 使用 PowerMock 和 Mockito 的 protected 构造函数测试类

android - Robolectric,点击列表项的问题

android - 如何让 Robolectric 选择特定的微调项

android - 空白页 Ionic 4 android 5.1

android - 底部导航 View 中加载的 fragment 在方向更改时变为空

android - 如何在对话框上应用默认主题

android - 由于 TypedArray 中缺少属性,导致 AppCompatButton 类膨胀时出错