Question

I'm trying to test some custom scrolling behavior that changes the location of a view based on how far down the user has scrolled. I discovered that even though the view will scroll in Robolectric 2.2, the height of the ListView (and everything else) is 0.

I read about the shadow objects and that we're supposed to call visible() when starting up the Activity so that it'll be drawn, and that's done. The default layout for a ListActivity is just a ListView with match_parent for height and width.

What's missing? Why doesn't the list have height?

@Test
public void testListActivity() {
    final ListActivity activity = Robolectric.buildActivity(ListActivity.class).create().start().resume().visible().get();

    ListView listView = activity.getListView();

    // Set up an adapter with items to scroll.
    final ArrayList<String> messages = new ArrayList<>();
    final int numberOfChildren = 100;
    for (int i = 0; i < numberOfChildren; i++) {
        messages.add("test");
    }

    final ArrayAdapter<String> listAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_dropdown_item_1line, messages);
    listView.setAdapter(listAdapter);
    Assert.assertEquals(listView.getCount(), numberOfChildren);

    Assert.assertTrue(listView.getHeight() > 0); // This fails.
}
Was it helpful?

Solution

Call populateItems() on the shadow of your listview after setting the adapter:

...
listView.setAdapter(listAdapter);

ShadowListView shadowListView = Robolectric.shadowOf(listView);
shadowListView.populateItems();

Assert.assertTrue(listView.getHeight() > 0);
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top