![](/img/trans.png)
[英]ViewBinding vs Kotlin Android Extensions with synthetic views
[英]Can we create custom Synthetic Kotlin Extensions in Android?
我对适用于 Android 的 Kotlin Synthetic Extensions 很感兴趣,并考虑是否可以对自定义文件(例如我们保留在项目中的原始 XML 文件)执行相同的操作。 例如,让我们考虑 Kotlin 中的合成视图。
import kotlinx.android.synthetic.main.fragment_profile_management.*
textview_shop_name.text = merchant.establishmentName
生成的代码是这样的:
TextView textView = (TextView) _$_findCachedViewById(com.goharsha.testapp.R.id.textview_shop_name);
Intrinsics.checkExpressionValueIsNotNull(textView, "textview_shop_name");
Merchant merchant3 = this.merchant;
if (merchant3 == null) {
Intrinsics.throwUninitializedPropertyAccessException("merchant");
}
textView.setText(merchant3.getEstablishmentName());
_$_findCachedViewById
方法也被生成到同一个类中,如下所示:
private HashMap _$_findViewCache;
public View _$_findCachedViewById(int i) {
if (this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View view = (View) this._$_findViewCache.get(Integer.valueOf(i));
if (view != null) {
return view;
}
View view2 = getView();
if (view2 == null) {
return null;
}
View findViewById = view2.findViewById(i);
this._$_findViewCache.put(Integer.valueOf(i), findViewById);
return findViewById;
}
由于这是特定于 Android 的,我猜这可以在 Kotlin 中完成,也许我可以将其扩展为自定义原始 XML 文件,例如配置文件,并将它们解析为一个对象可能会很有趣。
但是,我找不到如何做到这一点。 我知道 Kotlin 中的扩展函数,但在这里,一个完整的文件是基于导入合成生成的。 还有一个神奇的是,当我反编译应用程序时,没有找到这个 Kotlin 导入。
我还尝试查看 core-ktx 和 view-ktx 库,但到目前为止没有运气。 知道如何做到这一点吗?
是的,可以做到这一点,您需要做三件事才能做到这一点。
这些合成视图生成是在这条路线中完成的。 如果您想尝试制作这样的东西,这里有一些资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.