【问题标题】:How can I refactor my code in Kotlin without Casting?如何在不强制转换的情况下在 Kotlin 中重构我的代码?
【发布时间】:2020-01-20 16:10:59
【问题描述】:

我想知道,如何在没有像片段这样的活动投射的情况下编写代码?....

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

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

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

--------- MainActivity

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
    }

【问题讨论】:

  • 您可以使用接口或事件总线替换片段中的另一个片段,而不是强制转换活动(getActivity()),请参阅此答案stackoverflow.com/a/15007656/10097275
  • 你为什么想投?
  • 好吧,投射没有问题。但我只是想尝试使用 lambda 接口 :)

标签: android kotlin


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    is 是 Java 中 instanceof 的 kotlin 替代品


    tempMainImage.setOnClickListener {
        val message = "how are you today"
    
        if(activity is MainActivity) {
            activity?.onReplaceTtsFragment(message)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2020-08-08
      • 2014-09-27
      • 2013-05-23
      • 2012-07-13
      • 2013-01-09
      • 2010-12-31
      相关资源
      最近更新 更多