当我尝试在多模块应用程序中使用kotlin android extendions的视图注入时,我从android.library子模块注入视图时出错:
Unresolved reference: component_xyz_user_name
我们有一个主要的
应用程序
模块和一个android.library子模块
亚微米
在这两个模块中,gradle文件都包含:
apply plugin: 'com.android.library' //or com.android.application
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
[...]
dataBinding.enabled = true
androidExtensions.experimental = true
}
在subm库中,我们定义
组件\用户\信息.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data> [...] </data>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/component_xyz_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
</layout>
哪里
component_xyz_user_name
这样看:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>[...]</data>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/news_details_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include layout="@layout/component_user_info"
/>
</android.support.design.widget.CoordinatorLayout>
</layout>
MainFragmentViewModel
按以下方式定义:
import kotlinx.android.synthetic.main.component_user_info.*
class MainFragment : Fragment() {
fun updateUserInfo() {
component_xyz_user_name.text = "ABCDEF"
}
}
编译失败,出现以下错误:
e: /Users/user/repos/project/app/src/main/java/com/company/users/MainFragment.kt: (108, 9): Unresolved reference: component_xyz_user_name
e: /Users/user/repos/project/app/src/main/java/com/company/users/MainFragment.kt: (109, 9): Unresolved reference: component_xyz_user_name
为什么我会受伤
未解析的引用:组件\u xyz\u用户名
. 有什么解决办法吗?
编辑:
作为一个
临时解决办法
我已经为Activity&编写了以下扩展函数;片段:
/**
* Find view in an activity
*/
fun <T : View> Activity.v(@IdRes resId: Int): T = findViewById(resId)
/**
* Find view in a fragment
*/
fun <T : View> Fragment.v(@IdRes resId: Int): T = activity.findViewById(resId)
以便我可以:
fun updateUserInfo() {
v<TextView>(R.id.component_xyz_user_name).text = "ABCDEF"
}