【发布时间】:2020-10-16 08:41:55
【问题描述】:
我对 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 库,但到目前为止没有运气。知道如何做到这一点吗?
【问题讨论】:
-
您可以编写一个 Gradle 任务或插件来完成它。您可以使用 Android Studio 中的 File Watchers 插件在检测到文件更改时运行任务。
-
@Tenfour04 我知道 Gradle 插件方法,但是我必须生成新的源。这是导航安全 args Gradle 插件采用的方法。让我印象深刻的是,在这里我们的源代码在编译之前被修改了。新代码被添加到同一个类中,这在本质上是合成的。
标签: android kotlin extension-methods android-ktx