Skip to content

androiddevnotesyoutube/callback-example-kotlin

Repository files navigation

Callback Example Kotlin


How to create Callbacks in Kotlin?


Video Instructions: https://youtu.be/B-vb9porLPc


Android Badge androiddevnotes GitHub badge


Callback awesomedevnotes - androiddevnotes youtube thumbnail


Code

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView: TextView = findViewById(R.id.textView)

        fun someFunction(someCallback: SomeCallback) {
            val word = "nice"
            val letter = "12345"

            if (word.contains(letter)) {
                someCallback.onSuccess()
            } else {
                someCallback.onFailure("$word does not contain $letter")
            }
        }

        textView.setOnClickListener {
            someFunction(object : SomeCallback {
                override fun onSuccess() {
                    Toast.makeText(this@MainActivity, "Inside Success", Toast.LENGTH_SHORT).show()
                }

                override fun onFailure(error: String) {
                    Toast.makeText(this@MainActivity, "Inside Failure - $error", Toast.LENGTH_SHORT)
                        .show()
                }
            })
        }
    }
}

interface SomeCallback {
    fun onSuccess()
    fun onFailure(error: String)
}

💻 Find us on

About

Simple example of creating callbacks in Kotlin

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages