7

I have ListView with pictures and text. When I try to click item, I get 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 use the following code:

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

Can I click ListView using position of Adapter, without matches or startWith?

Marcus
  • 6,697
  • 11
  • 46
  • 89
Aleksandr Gorshkov
  • 473
  • 1
  • 6
  • 16
  • 3
    This means you have multiple views with the named ID in the view hierarchy. Can you post the whole error message? – haffax Jan 19 '15 at 22:32
  • 1
    Yes, sure. But full error is too long.http://pastebin.com/eahDGDMb – Aleksandr Gorshkov Jan 20 '15 at 07:06
  • 2
    From looking at the whole hierarchy it seems that you have a ViewPager which shows multiple pages with three of them having an AdapterView with the ID cardsGridView. So you have one AdapterView, the ViewPager, with another nested AdapterView, your ListView. What may work is to give the Views returned from Adapter.getView individual IDs or Tags and use a isDescendantOf() matcher in your inAdapterView() call together with the withId. – haffax Jan 20 '15 at 22:02
  • haffax, can you give the example of code, please? I can't find it? – Aleksandr Gorshkov Jan 27 '15 at 06:48

3 Answers3

10

Try with atPosition(). e.g.

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.

user846316
  • 6,037
  • 6
  • 31
  • 40
  • For long lists, I find it necessary to scroll to the item incrementally, or gradually, before performing the selection via click(). This was more obvious if running on Android 13 than before. – barnabas Feb 28 '23 at 18:06
0

Use Record Test to obtain the ViewInteraction of the list then obtain the view and use performItemClick 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));
    });
}
Stoica Mircea
  • 782
  • 10
  • 22
0

Try this one:

onView(withText("ListItemText")).perform(ViewActions.click());
Raghwendra Sonu
  • 471
  • 3
  • 7