繁体   English   中英

如何在没有 Casting 的情况下在 Kotlin 中重构我的代码?

[英]How can I refactor my code in Kotlin without Casting?

我想知道,如何在没有像片段那样进行活动转换的情况下编写代码?....

--------- 一个片段

        tempMainImage.setOnClickListener {
            val message = "how are you today"

            (activity as? MainActivity).let {
                it?.onReplaceTtsFragment(message)
            }
        }

- - - - - 主要活动

fun onCloseTtsFragmentLayout() {
        detailFragmentLayout.visibility = View.GONE
    }

    fun onReplaceTtsFragment(message: String) {
        supportFragmentManager.beginTransaction().replace(R.id.detailFragmentLayout, TtsDetailFragment.newInstance(message, ::onCloseTtsFragmentLayout)).commit()

        detailFragmentLayout.visibility = View.VISIBLE
    }

为什么不尝试使用when块和is关键字。

tempMainImage.setOnClickListener {
    val message = "how are you today"

    when (activity) {
        is MainActivity -> activity.onReplaceTtsFragment(message)
        else -> return
    }

is是 java 中instanceof的 kotlin 替代品


tempMainImage.setOnClickListener {
    val message = "how are you today"

    if(activity is MainActivity) {
        activity?.onReplaceTtsFragment(message)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM