Android - Anything similar to the iPhone SDK Delegate Callbacks?

Viewed 22860

I just switched over from iPhone to Android and am looking for something similar to where in the iPhone SDK, when a class finishes a certain task, it calls delegate methods in objects set as it's delegates.

I don't need too many details. I went through the docs and didn't find anything (the closest I got was "broadcast intents" which seem more like iOS notifications).

Even if someone can point me to the correct documentation, it would be great.

Thanks!

6 Answers

The pendant for kotlin.

Define your interface: In my example I scan a credit card with an external library.

interface ScanIOInterface {
     fun onScannedCreditCard(creditCard: CreditCard)
}

Create a class where you can register your Activity / Fragment.

class ScanIOScanner {
  var scannerInterface: ScanIOInterface? = null

  fun startScanningCreditCard() {
      val creditCard = Library.whichScanCreditCard() //returns CreditCard model
      scannerInterface?.onScannedCreditCard(creditCard)
  }
}

Implement the interface in your Activity / Fragment.

class YourClassActivity extends AppCompatActivity, ScanIOInterface {
    //called when credit card was scanned
    override fun onScannedCreditCard(creditCard: CreditCard) {
        //do stuff with the credit card information
    }

    //call scanIOScanner to register your interface
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)

       val scanIOScanner = ScanIOScanner()
       scanIOScanner.scannerInterface = this
    }
} 

CreditCard is a model and could be define however you like. In my case it includes brand, digits, expiry date ...

After that you can call scanIOScanner.startScanningCreditCard() wherever you like.

Kotlin's official Delegation pattern:

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(b: Base) : Base by b 

fun main() {
    val b = BaseImpl(10)
    Derived(b).print()
}

See: https://kotlinlang.org/docs/delegation.html

Related