简体   繁体   中英

In Kotlin, how does a constructor with anonymous class work?

Consider a functionality F, which depends on Android lifecycle methods. I have implemented this functionality in an Activity A. Any other activity which wants to implement this functionality can simply extend A. The results are sent back to the child activity via an interface. Example:

// interface
interface ACallbacks {
     fun onResult(string: String)
}

// Activity A
open class AActivity
(private val aCallbacks: ACallbacks): AppCompatActivity() {
     // functionality F, which depends on Android lifecycle methods
}

// Activity B
class BActivity: AActivity(object: ACallbacks {
    override fun onResult(string: String) {
         // Q: how to use string in BActivity?
    }
}) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_b)
    }
}

How to access the result from Activity A (ie, string ) in Activity B. For example, how do I set it in a textView present in Activity B?

If BActivity inherits from AActivity - inside BActivity you can get what you want:

override fun someFun(): String {
    val parentResult = super.someFun()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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