首页 > 解决方案 > 将接口从片段传递到kotlin中的活动

问题描述

我想将我的界面对象从我的片段传递给我在 Kotlin 中的新活动。我尝试通过发送作为构造函数参数不起作用。我已经尝试发送本地广播...不工作。下面是代码。

我的活动.kt

class Myactivity: Activity{
    // get interface ref object here
    interface Myinterface: Parcelable {
        fun someMethod(true:Boolean?)
    }
}

我的片段.kt

class Myfragment: Fragment(), Myinterface{
    val interface: Myinterface
    val intent = Intent(activity,Myactivity::class.java)
    intent.putextra // or   putParcelableExtra??? // pass interface obj

    override fun someMethod(true:Boolean?) {

    }
}

现在我已经在我的片段中实现了它,并且我想通过意图将相同的引用传递回我的活动。我怎样才能在 Kotlin 中实现这一点?

任何帮助深表感谢。TIA

标签: androidkotlinandroid-activityinterfacefragment

解决方案


一种可能且更简单的解决方案是从Serializable

interface MyInterface : Serializable {
    fun someMethod()
}

并有意地通过它。

val intent = Intent(activity, Myactivity::class.java).apply {
    putExtra("interface", this@Myfragment)
}

推荐阅读