• Latest Code...

    Featured Post

    Implementing Hilt in a Kotlin Android Jetpack Compose Project with MVVM Architecture

     In modern Android development, maintaining a scalable codebase can be challenging, especially when it comes to dependency management. Hilt,...

    Solution: “Type inference failed” error by using "findViewById” in Kotlin

    If you get any error when you are using kotlin and references views to kotlin, then most of time every developer faced  “Type inference failed” error  in Kotlin.

    We have few option for such kind of error in kotlin,


    var tvName = findViewById(R.id.txtName) as TextView
    
    
    to
     
    var tvName = findViewById<TextView>(R.id.txtName) 
    
    You can use Kotlin Android Extensions too for that. Check the doc here.

    Kotlin Android Extensions:

    • In your app gradle.build add apply plugin: 'kotlin-android-extensions'
    • In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout. for example activity_main
    • That's it, you can call TextView directly in your code.
    Sometimes its works like this:

    var tvName:TextView = findViewById(R.id.txtName) as TextView
    If you are using Anko, then you have to do this:
    
    
    var tvName:TextView = find(R.id.txtName)
    Where bind internally work like this:
    
    
    fun <T : View> Activity.bind(@IdRes res : Int) : T {
        @Suppress("UNCHECKED_CAST")
        return findViewById(res) as T}
    More info:
    https://kotlinlang.org/docs/tutorials/android-plugin.html
    https://blog.jetbrains.com/kotlin/2015/04/announcing-anko-for-android/
    https://developer.android.com/sdk/api_diff/26/changes.html
    #HappyCoding #ILoveKotlin #PrAndroid
    
    

    Contact Form

    Name

    Email *

    Message *