为什么findViewById在robolectric-unit-test中的膨胀布局上返回null?

时间:2013-01-25 17:30:40

标签: android robolectric

我正在尝试用Robolectric测试一些代码。

我的代码使布局膨胀,然后通过在此布局上调用findViewById来尝试检索视图。布局通胀工作正常。但是,此布局上的findViewById始终返回null。

我可以在调试器中看到膨胀布局的所有(阴影)子视图都在那里并且设置了它们的属性。但每个孩子的id都设为0.为什么?我错过了什么吗?

设备或仿真器(没有robolectric)上的实际代码工作正常,但是当我尝试使用robolectric运行它时,它会失败,如上所述。

基本上我的代码如下:

LayoutInflater inflater = (LayoutInflater) Robolectric.application.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.timeline_list_item, null);
TextView view = (TextView) layout.findViewById(R.id.listItem_date);
//why is view null here!
view.setText("test");

此致 弗兰克

2 个答案:

答案 0 :(得分:3)

谢谢,我发现了问题。

我的资源标识符R.id.listItem_date在我的资源xml文件中声明为@+id/listItem.date

Android似乎转换为“。”在生成的R文件中名称为“_”。这在编译和运行代码时工作正常,但显然robolectric存在问题。

当我将资源名称中的点更改为下划线时,我的robolectric代码工作正常。

既然我知道该找什么,我发现有一个开放的错误票: https://github.com/pivotal/robolectric/issues/265

答案 1 :(得分:0)

请参阅以下更改

LayoutInflater inflater = (LayoutInflater)**"ContextOnject"**.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.timeline_list_item, null);