Home > Mobile >  How to solve error with View Binding in Kotlin
How to solve error with View Binding in Kotlin

Time:02-03

Here I'm getting this error

A screenshot of the code below, with ActivityShoppingBinding in red

package lk.ac.kln.mit.stu.mobileapplicationdevelopment.activities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View.inflate
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import lk.ac.kln.mit.stu.mobileapplicationdevelopment.R

class ShoppingActivity : AppCompatActivity() {

    val binding by lazy{
        ActivityShoppingBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shopping)
        setContentView(binding.root)

        val navController = findNavController(R.id.shoppingHostFragment)
        binding.bottomNavigation.setupWithNavContoller(navController)
    }
}

Anyone know the reason to fail this code? I tried adding below lines to the gradel as well

buildFeatures {
    viewBinding true
}

CodePudding user response:

You can better use this, this way the binding can be set in the onCreate as before this it can not build UI components.

var binding: ActivityShoppingBinding? = null

override fun onCreate(savedInstanceState: Bundle?) {
    binding = ActivityShoppingBinding.inflate(layoutInflater)

    binding?.let {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shopping)
        setContentView(binding.root)

        val navController = findNavController(R.id.shoppingHostFragment)
        binding.bottomNavigation.setupWithNavContoller(navController)
    }
}

CodePudding user response:

ActivityShoppingBinding is in red because it's not recognised by the IDE - usually this means you haven't imported it, so it doesn't know what it is. And you don't have an import line for that class, so that's probably your problem!

The easiest fix is just to put your cursor over the error and do Alt Enter (or whatever) or click the lightbulb icon that appears, and the IDE will offer to import it for you. Once that binding class is imported it should work fine.


Also you're calling setContentView twice - that's pointless (you're inflating a layout then throwing it away immediately) and it can introduce bugs if you accidentally set things on a layout that isn't being displayed. You should only be calling it once, with binding.root in this case.

You might want to look at the recommended way of initialising view binding in Activities (and the Fragments section too if you're using them). Avoid using lazy for UI stuff, since it can only be assigned once you can run into issues (mostly with Fragments, but the example in that link uses lateinit too)

  • Related