Android Espresso ListView click item

I have a ListView with images and text. When I try to click an item, I get an error

 android.support.test.espresso.AmbiguousViewMatcherException: 'with id: com.cifrasoft.telefm:id/cardsGridView' matches multiple views in the hierarchy. Problem views are marked with '****MATCHES****' below. 

I am using the following code:

 onData(hasToString(startsWith("Item Text"))) .inAdapterView(withId(R.id.cardsGridView)) .perform(click()); 

Is it possible to click ListView using the Adapter position, without matches or startWith ?

+7
android android-listview android-espresso ui-testing
source share
2 answers

Try with atPosition (). eg.

 onData(hasToString(startsWith("Item Text"))) .inAdapterView(withId(R.id.cardsGridView)).atPosition(0) .perform(click()); 

with index 0, it will click on the first matching view found.

+10
source share

Use Record Test to get the ViewInteraction list, then get the view and use executeItemClick as follows:

 AtomicReference<ListView> resultView = new AtomicReference<>(null); ViewInteraction viewInteraction1 = onView( ... withId(R.id.my_list_id), ...); viewInteraction1.check(((view, noViewFoundException) -> { if(noViewFoundException != null){ return; } resultView.set((ListView) view); })); if(resultView.get() != null){ ListView listView = resultView.get(); activity.runOnUiThread(()->{ listView.performItemClick( listView.getAdapter().getView(index, null,null), index, listView.getAdapter().getItemId(index)); }); } 
0
source share

All Articles