1

的文本。如果我有,我可以通過訪問「AppCompatTextView」元素:咖啡 - 獲得元素

onView(withId(R.id.allergies_text)) 

從佈局督察:

enter image description here

有沒有一種方法,我可以訪問Android Studio中元素的文本? (訪問任何文字是有...不檢查的元素存在一些文本)

我試圖做的:

val tv = onView(withId(R.id.medical_summary_text_view)) as TextView 
val text = text.text.toString() 
print(text) 

但我得到的錯誤:

android.support .test.espresso.ViewInteraction無法轉換爲android.widget.TextView

回答

2

您應該創建一個匹配器來訪問該元素值。

舉例來說,你可以檢查它是否文本有一定的價值:

Matcher<View> hasValueEqualTo(final String content) { 

    return new TypeSafeMatcher<View>() { 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("Has EditText/TextView the value: " + content); 
     } 

     @Override 
     public boolean matchesSafely(View view) { 
      if (!(view instanceof TextView) && !(view instanceof EditText)) { 
        return false; 
      } 
      if (view != null) { 
       String text; 
       if (view instanceof TextView) { 
        text = ((TextView) view).getText().toString(); 
       } else { 
        text = ((EditText) view).getText().toString(); 
       } 

       return (text.equalsIgnoreCase(content)); 
      } 
      return false; 
     } 
    }; 
} 

,並調用它是這樣的:

onView(withId(R.id.medical_summary_text_view)) 
    .check(matches(hasValueEqualTo(value))); 

,或者你可以編輯這個匹配返回文本僅僅是空或不:

Matcher<View> textViewHasValue() { 

    return new TypeSafeMatcher<View>() { 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("The TextView/EditText has value"); 
     } 

     @Override 
     public boolean matchesSafely(View view) { 
      if (!(view instanceof TextView) && !(view instanceof EditText)) { 
        return false; 
      } 
      if (view != null) { 
       String text; 
       if (view instanceof TextView) { 
        text = ((TextView) view).getText().toString(); 
       } else { 
        text = ((EditText) view).getText().toString(); 
       } 

       return (!TextUtils.isEmpty(text)); 
      } 
      return false; 
     } 
    }; 
} 

,並調用它是這樣的:

onView(withId(R.id.medical_summary_text_view)) 
    .check(matches(textViewHasValue()));