Android Data Binding crash when using include tag with custom view layout Android Data Binding crash when using include tag with custom view layout xml xml

Android Data Binding crash when using include tag with custom view layout


I took a look at your project and ran it. I think the reason it is crashing is because of

@Override protected void onFinishInflate() {    super.onFinishInflate();    DataBindingUtil.bind(this);}

if you remove DataBindingUtil.bind(this) it will stop crashing. The reason being that the bind call is looking for a <layout>surrounding the view but it can't find it so it throws an exception. Since the CustomView is calling bind on itself it is not surrounded by anything causing ViewDataBinding to throw new IllegalArgumentException("View is not a binding layout")

I'm not entirely sure what you're trying to achieve but calling bind inside of onFinishInflate would be redundant since the activity is doing that for you when it binds the layout for the activity. If you require the binding within the CustomView class you can do the following:

@Override protected void onAttachedToWindow() {  super.onAttachedToWindow();  CustomViewBinding binding = DataBindingUtil.findBinding(this);}


In case anyone else makes the er..dumb mistake I did...

This error was happening to me when I mistakenly had two duplicate layout files, one using databinding, and the other not...

Removing the duplicate fixed the error for me.


@SeptimusX75's answer doesn't work, because DataBindingUtil.findBinding(this) calls this.getTag(R.id.dataBinding) internally to get the binding, but the tag hasn't been set yet when onFinishInflate is called.

Instead, try to get the binding via this.getTag(R.id.dataBinding); when you need the use the binding.

public class CustomView extends LinearLayout {    // ...    public CustomViewBinding binding;    // ...    public void setTitle(final String text) {        if (binding == null) {            binding = Objects.requireNonNull(getTag(R.id.dataBinding));        }        binding.title.setText(text);    }}

Alternatively, set the binding manually from the activity before calling any method on the CustomView.

public class CustomView extends LinearLayout {    // ...    public CustomViewBinding binding;    // ...    public void setBinding(final CustomViewBinding binding) {        this.binding = binding;    }}
public class MainActivity extends AppCompatActivity {    @Override protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        CustomViewBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);        binding.customView.getRoot().setBinding(binding.customView);    }}