android - 为 kotlin 扩展函数的基础对象附加上下文
问题描述
这个问题专门针对Android开发中使用的Kotlin扩展功能。
因此,Kotlin 为我们提供了将某些扩展行为添加到类中以扩展基于类行为的能力。
示例:(取自我当前的 Android 项目,用于 Espresso 测试中的 viewAssertion)
fun Int.viewInteraction(): ViewInteraction {
return onView(CoreMatchers.allOf(ViewMatchers.withId(this), ViewMatchers.isDisplayed()))
}
在我的用例中,我可以像这样使用它:
R.id.password_text.viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())
一切都很好,除了这个扩展函数为所有Int
对象提供了扩展行为,而不仅仅是 Android 中的 View ID,这一点都不好。
问题是是否有任何方法可以为此提供上下文Int
,例如在 Android 中,我们在 Android 中为上述给定情况提供了@IdRes 支持注释?
解决方案
您无法区分资源中的 Int 和普通 Int。它是同一个类,您正在向所有 Int 类型的类添加扩展。
另一种方法是创建自己的 Int 包装器:
class IntResource(val resource: Int) {
fun viewInteraction(): ViewInteraction {
return onView(CoreMatchers.allOf(ViewMatchers.withId(resource), ViewMatchers.isDisplayed()))
}
}
然后我们像这样:
IntResource(R.id.password_text).viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())
推荐阅读
- r - geom_col over year and groups:有什么方法可以避免在酒吧分界?
- java - 允许通知 Android webview
- python - 尝试确定代码中是否存在 S3 路径
- python - Python HTTP Server - TypeError:需要一个类似字节的对象,而不是'str'
- mongodb - 单个查询有条件的不同操作 - MongoDb
- sql - SQL 查找每个帐户的下一个唯一日期和子帐户
- r - 在R中获取直方图的bin宽度
- string - oracle字符串函数的开始和结束位置
- javascript - 更改光标状态时是否可以添加过渡?
- android-studio - 热门从片段导航到活动