【问题标题】:Kotlin synthetic extension for view用于视图的 Kotlin 合成扩展
【发布时间】:2017-09-19 22:07:32
【问题描述】:

我有一个包含一些视图的布局,其中一个的 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
    }
}

我尝试使用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>

我的错误在哪里?

【问题讨论】:

    标签: android kotlin kotlin-android-extensions kotlin-extension


    【解决方案1】:

    错误试图告诉您的是,您只能从ActivityFragment 中访问带有扩展的视图。这是因为查找具有给定 ID 的视图的操作与您手动执行的操作完全相同,它只是调用 Activity.findViewById()Fragment.getView().findViewById(),然后将类型转换为 @987654325 的特定子类@。我猜你的控制器不是ActivityFragment

    还有另一种使用扩展的方法,如果你能以某种方式将你的布局的根视图传递给你的控制器。然后您可以执行以下操作:

    val title: TextView = rootView.title_whalemare
    

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

    【讨论】:

    • 这种情况下写:import kotlinx.android.synthetic.main.*.
    • 如果你的类是fragment或activity类,那么你应该使缓存失效并重新启动,错误就会消失。如果您在片段/活动之外执行此操作,那么您需要完全按照答案所述进行操作。
    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 2018-02-16
    • 2020-09-10
    相关资源
    最近更新 更多