【发布时间】:2019-08-19 15:58:28
【问题描述】:
我知道Kotlin的Android Extensions创建了合成属性+缓存功能来代替任何需要调用findViewById:
- https://stackoverflow.com/a/46482618/1650674
- https://www.raywenderlich.com/84-kotlin-android-extensions
- https://antonioleiva.com/kotlin-android-extensions/
所有这些示例都表明类似的 java 代码看起来像
private HashMap _$_findViewCache;
...
public View _$_findCachedViewById(int var1) {
if(this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1));
if(var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(Integer.valueOf(var1), var2);
}
return var2;
}
public void _$_clearFindViewByIdCache() {
if(this._$_findViewCache != null) {
this._$_findViewCache.clear();
}
}
我不明白这如何防止潜在的 NPE? var2 = this.findViewById(var1); 仍可能返回 null。
使用最后一个链接中的示例:
<TextView
android:id="@+id/welcomeMessage"
...
android:text="Hello World!"/>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
welcomeMessage.text = "Hello Kotlin!"
}
welcomeMessage 是什么类型? TextView 或 TextView?
【问题讨论】:
标签: android kotlin kotlin-android-extensions