Kotlin合成扩展视图

wha*_*are 15 kotlin kotlin-extension kotlin-android-extensions

我有一些带有一些视图的布局,其中一个有id title_whalemare

import kotlinx.android.synthetic.main.controller_settings.*
import kotlinx.android.synthetic.main.view_double_text.*

class MainSettingsController : BaseMvpController<MvpView, MvpPresenter>() {

    val title: TextView = title_whalemare

    override fun getLayout(): Int {
        return R.layout.controller_settings
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试找到它kotlin extensions,但我不能,因为我得到以下错误

由于接收器类型不匹配,以下候选者均不适用 由于接收器类型不匹配,以下候选者均不适用

controller_settings.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title_whalemare"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我的错误在哪里?

zsm*_*b13 24

该错误试图告诉您的是,您只能通过Activitya或a中的Extensions访问视图Fragment.这是因为它完全一样的事情找到与给定的ID作为什么你会做手工,它只是调用的意见Activity.findViewById()Fragment.getView().findViewById(),然后做类型转换到特定的子类View.我猜你的控制器不是Activity或者Fragment.

如果你可以以某种方式将布局的根视图传递给控制器​​,还有另一种使用扩展的方法.然后你可以做以下事情:

val title: TextView = rootView.title_whalemare
Run Code Online (Sandbox Code Playgroud)

同样,这只是替换了View.findViewById()调用和类型转换.