0

的LinearLayout(productList的)在運行時與孩子的意見被動態填充,如以下時:咖啡AmbiguousViewMatcherException試圖點擊一個圖標(TextView的)

@ViewById(R.id.ll_products) 
LinearLayout productList; 

public void createProductList() { 
    productList.addView(getView(mobilePhone)) 
    productList.addView(getView(internet)) 
    productList.addView(getView(television)) 
} 

public View getView(Product product) { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    TextView layout = (LinearLayout) inflater.inflate(R.layout.row_product, null); 
    TextView productIcon = (TextView) layout.findViewById(R.id.tv_product_row_icon); 
    productIcon.setText(product.getProductIcon()); 
    productName.setText(product.getName()); 
} 

productList的是故意的LinearLayout,而不是ListView控件。

產品清單有三個產品 - 每個產品都有圖標(可以重複)。

我想記錄一個場景,我點擊圖標的第二個產品。 這樣的場景如何避免AmbiguousViewMatcherException?

不幸的是,下面的代碼將無法正常工作 - 三R.id.tv_product_row_icon會發現...

ViewInteraction appCompatTextView = onView(withId(R.id.tv_product_row_icon)); 
    appCompatTextView.perform(scrollTo(), click()); 

如何指定第二圖標被點擊?

回答

2

不幸的是,您將不得不爲這種情況創建自定義Matcher

以下的View與指定索引相匹配:適合你的情況

public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { 
    return new TypeSafeMatcher<View>() { 
     int currentIndex = 0; 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("with index: "); 
      description.appendValue(index); 
      matcher.describeTo(description); 
     } 

     @Override 
     public boolean matchesSafely(View view) { 
      return matcher.matches(view) && currentIndex++ == index; 
     } 
    }; 
} 

用法:

Matcher<View> secondIconMatcher = allOf(withId(R.id.tv_product_row_icon)); 
onView(withIndex(secondIconMatcher , 1)).perform(click()); 
+0

它的偉大工程!謝謝! 但是,我有一個情況,我有5個圖標 - 最後一個圖標只有在滾動後才能在屏幕上顯示。當我使用你的解決方案時,我得到一個異常 - NoMatchingViewException:沒有層次結構中的視圖找到匹配:索引:<4>。 任何想法可能會造成這種情況? –

+1

你自己回答了你的問題 - 視圖在屏幕上不可見。解決方案是匹配如果視圖可見:'onView(matcher).check(matches(isDisplayed()));'在try-catch塊內部。如果拋出異常,則應該滾動父視圖。 –