'How to return fragment_title correctly?ActivityMain error using DataBinding

I know that this question has been answered 100 times but my code just doesn't work and I can't figure out what is wrong with it by reading posts made by others.

I want to make an app where when you open it u get a search filed, you tipe what u want to search and then click enter and you get what you searched for.

So, I'm trying to use DataBinding for that. In the activity xml file i wrapped everything with the layout tag :

<?xml version="1.0" encoding="utf-8"?>

<layout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<fragment
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/TitleFragment"

    />

</layout

And here is my MainActivty:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    @Suppress("UNUSED_VARIABLE")
    val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}

}

and my TitleFragment:

class TitleFragment : Fragment() {
//Inflating and Returning the View with DataBindingUtil

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_title, container, false)
}

}

I just want to be able to open the app with the fragment_title.xml showing via the activity_main as i want to use databinding for opening my views. I keep getting the error "Unresolved reference: ActivityMainBinding" but in the build.gradle i included databinding=true

viewbinding=true

but nothing works. How do i fix this error and did i even return the fragment correctly?



Solution 1:[1]

TitleFragment

private var _binding: FragmentTitleBinding? = null
    private val binding get() = _binding!!

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    _binding = FragmentHomeBinding.inflate(inflater, container, false)
//...this is code ...
return binding.root
}

MainActivity

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityDoctorHomeBinding.inflate(layoutInflater)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1