这里是 Kotlin 的片段:
fun withBackgroundColorResId(@IdRes expectedId: Int): Matcher<Any> {
return object : BoundedMatcher<Any, Any>(Any::class.java) {
override fun matchesSafely(view: Any): Boolean {
if (view !is View || view !is ViewGroup) {
Log.w(TAG, "withBackgroundColorResId_incorrect_type, view = $view")
return false
}
val currenColor = (view.background.current as ColorDrawable).color
val expectedColor = ContextCompat.getColor(view.context, expectedId)
return currenColor == expectedColor
}
override fun describeTo(description: Description) {
description.appendText("textView with background color resId: ")
description.appendValue(context.getResources().getString(expectedId))
}
}
}
和用法:
onView(withRecyclerView(tradersRecyclerView).atPositionOnView(traderCheckPos, pauseTextView)).check(matches(withBackgroundColorResId(trade_not_running_color)))
在这里logcat:
06-05 10:25:12.787 I/ViewInteraction(22053): Checking 'MatchesViewAssertion{viewMatcher=textView with background color resId: "#ffbde6ff"}' assertion on view RecyclerView with id: com.myproject.debug:id/tradersRecyclerView at position: 0
06-05 10:25:12.787 W/com.myproject.custom.matcher.CustomMatchers(22053): withBackgroundColorResId_incorrect_type, view = androidx.appcompat.widget.AppCompatTextView{a412c35 V.ED..C.. ........ 0,0-288,288 #7f0800c9 app:id/pauseTextView}
06-05 10:25:12.794 D/com.myproject.activity.TradersActivityTest(22053): afterEach
06-05 10:25:12.794 I/MockWebServer(22053): MockWebServer[8081] done accepting connections: Socket closed
06-05 10:25:12.825 D/LifecycleMonitor(22053): Lifecycle status change: com.myproject.ui.activity.TradersActivity@2964795 in: PAUSED
06-05 10:25:12.825 D/LifecycleMonitor(22053): running callback: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558
06-05 10:25:12.825 D/LifecycleMonitor(22053): callback completes: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558
如您所见,对象“视图”具有类型androidx.appcompat.widget.AppCompatTextView
。正如我们所知,AppCompatTextView
是从View
但为什么它打印
withBackgroundColorResId_incorrect_type, view = androidx.appcompat.widget.AppCompatTextView
?
在 Kotlin 的文档中is
指出:
检查值是否具有特定类型
所以根据你的代码,你以某种方式询问
是我的 X 视图实例吗?
按照这条线你得到:
view instanceof View
?答案是肯定的。view instanceof ViewGroup
?答案是否定的。单个视图主要由 View 类扩展。ViewGroups在更复杂的布局像大多采用LinearLayout
,FrameLayout
等等。
总结结果,你有:
true||false
= 真
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句