Home > other >  DataBindingUtil.setContentView | Not enough information to infer type variable T
DataBindingUtil.setContentView | Not enough information to infer type variable T

Time:01-06

When i use view binding it works fine but when i use data binding i receive errors

My Imports :

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.shoestore.R
import com.example.shoestore.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint

My code :

   val binding  = DataBindingUtil.setContentView(this, R.layout.activity_main)

Error message :

Not enough information to infer type variable T

gradle :

    buildFeatures {
        dataBinding = true
        viewBinding = true
    }
  • I tried to disable view binding thought that it conflict with data binding generated classes

  • I tried the android studio auto complete thought that i typed it wrong and the auto complete was expecting type of ViewDataBinding!

    val binding  = DataBindingUtil.setContentView<>(this, R.layout.activity_main)

error message for this code :

Type expected
  • tried to smart cast and it worked but i cant access the views only the root
val binding  = DataBindingUtil.setContentView(this, R.layout.activity_main) as ViewDataBinding

CodePudding user response:

You can try it like this. In Your Activity or Fragment

  • set ContentView In Fragment

     private var binding1: FragmentAddItemBinding? = null
     private val binding get() = binding1!!
    
     override fun onCreateView(
     inflater: LayoutInflater,
     container: ViewGroup?,
     savedInstanceState: Bundle?
    ): View? {
     binding1 = FragmentAddItemBinding.inflate(inflater, container, false)
    
     //Here is your code
    
     return binding.root
    }
    
  • set ContentView In the Activity

    private var binding : ActivityMainBinding? = null
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
    
      binding = ActivityMainBinding.inflate(layoutInflater)
      setContentView(binding!!.root)
    
     //Your Code is here 
    
     }
    

It's Work for me so I just hope this work for you

CodePudding user response:

you need to mention the type of variable binding like this:

val binding : ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

instead of

val binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

This should solve the issue

  • Related