在 kotlin 上,textview 未在 onCreate 方法之外初始化

on kotlin, textview not initialized outside onCreate method

我是 Kotlin 的新手,正在尝试实施 MVP 架构,

目前我在 onCreate() 方法之外遇到问题 initializing/setting textview 的值 这是我的代码

SplashActivity.kt

class SplashActivity : AppCompatActivity(), Splash.ViewInterface {
lateinit var appDetail: AppDetail
lateinit var textTitle: TextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    textTitle = findViewById(R.id.splash_txt_title) as TextView

    AppSingleton.appContext = applicationContext

    var splashPresentation = SplashPresentation(this)
    splashPresentation.getAppDetailFromService()
}

override fun fetchAppDetailSuccessful(response: SplashServiceObject) {
    AppSingleton.initializeAppDetal(Gson().fromJson(response.json_string, AppDetail::class.java))
    this.appDetail = AppSingleton.appDetail
}

override fun fetchAppDetailFailed(errMsg: String) {
    textTitle.text = errMsg
}
}

SplashPresenter.kt

class SplashPresentation(private val view: Splash.ViewInterface) : Splash.PresentationInterface {

fun getAppDetailFromService() {
    var splashService = SplashService()
    splashService.getAppDetailFromAssets(this)
}

override fun fetchAppDetailFromServiceSuccessful(response: SplashServiceObject) {
    view.fetchAppDetailSuccessful(response)
}

override fun fetchAppDetailFromServiceFailed(errMsg: String) {
    view.fetchAppDetailFailed(errMsg)
}
}

SplashService.kt

 class SplashService {
fun getAppDetailFromAssets(splashPresentation: SplashPresentation) {
    val json_filename = "appdetail.json"
    var jsonResponse: JsonResponse = AppSingleton.commonUtils.fetchJsonFromAssets(json_filename, AppSingleton.appContext!!)
    if (jsonResponse.json_status) {
        var splashServiceObj = SplashServiceObject
        splashServiceObj.json_string = jsonResponse.json_info
        splashServiceObj.response_msg = "JSON Successful fetched."
        splashPresentation.fetchAppDetailFromServiceSuccessful(splashServiceObj)
    } else {
        splashPresentation.fetchAppDetailFromServiceFailed(jsonResponse.json_info)
    }
}
}

在我的 SplashActivity().onCreate() 中,我正在调用一个访问服务的 Presenter,然后该服务 return 是 Presenter 的一个值,
然后 Presenter,return 值到我的 SplashActivity 的视图,其中一个功能是,fetchAppDetailFailed(errMsg)

当我 运行 应用程序时,它崩溃了,提示 "textaa" 尚未初始化。
回到 Java exp,当变量已经在 onCreate() 上实例化时,你可以在 activity 中的任何地方调用这个变量。

提前致谢!

您不能在 Android 上实例化 Activity。它们由 OS 实例化,OS 调用它的生命周期方法。

在 MVP 模式中,View 和 Presenter 都相互引用。由于 Activity(视图)是应用程序的入口点,您的 Activity 应该实例化 Presenter 并将其自身的引用传递给 Presenter,以便双向通信。

此外,Presenter 中对 activity 的引用应指定为 ViewInterface,而不是 Activity,否则您有点违背了使用 MVP 的目的。

class SplashPresentation(private val view: Splash.ViewInterface) : Splash.PresentationInterface {

    //... methods that call functions on view
}

class SplashActivity : AppCompatActivity(), Splash.ViewInterface {

    private val presenter = SplashPresentation(this)

    //...

}