【问题标题】:Android InstrumentationTestCase on custom view using resource, not found使用资源的自定义视图上的 Android InstrumentationTestCase,未找到
【发布时间】:2016-03-17 22:15:37
【问题描述】:

我有一个动态创建视图的自定义视图。

public class MyCustomView extends LinearLayout {
    ...
    private View foo() {
        View view = new View(getContext());
        view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.gray));
        return view;
    }
}

当我测试 foo() 时,我得到一个资源未找到异常。

public class MyCustomViewTest extends InstrumentationTestCase {
    ...
    public void testFoo() {
        View view = myCustomView.foo();
        assertNotNull(view);
    }
}

android.content.res.Resources$NotFoundException: Resource ID #0x7f0c0022

如何获得测试以查看我的颜色资源?

【问题讨论】:

    标签: android android-custom-view android-instrumentation


    【解决方案1】:

    可以通过 getTargetContext() 实现。我以前有

    myCustomView = new MyCustomView(getInstrumentation().getContext());
    

    替换为

    myCustomView = new MyCustomView(getInstrumentation().getTargetContext());
    

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多