Search code examples
androidandroid-databindingandroid-viewbinding

Can you use dataBinding and ViewBinding in the same activity?


I would like to use ViewBinding and DataBinding in the same activity. If this is possible how would you go about implementing it in an activity?

Here is what I've tried so far,

@Override
protected void onCreate(Bundle savedInstanceState) {
    ActivityMainBinding viewBinding = ActivityMainBinding.inflate(getLayoutInflater();
    View view = viewBinding.getRoot();
    setContentView(view)

    ActivityMainBinding  dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

}

Solution

  • ViewBinding was created because some people were using DataBinding just to get the binding class in the java/kotlin code and use the references (as opposed to setting values directly in xml using the data field). Data binding includes everything that ViewBinding has, so it wasn't designed to work side by side with View binding.

    The biggest issue is the naming conflict between the generated classes. Both ViewBinding and DataBonding would want to generate the class MainLayoutBinding for the layout main_layout.xml.

    Now there may be a work around using custom naming, but its not really worth it, and here's why:

    Most likely the only reason you'd want both is so that you don't have to wrap your all your xml in the <layout>...</layout>and get the binding by default, but that's such a small amount of effort that its not really worth making both libraries work side by side.

    If you want to set data in xml just use Data Binding, and just make it a standard practice wrap all your xml with <layout> so you can always have a reference to the views through a binding class.

    If you don't want to set data in xml, just use View Binding.

    But if you REALLY wanna do it, I think you can set the data binding name using this:

    <data class="DataBindingName">
        </data>