DataBindingUtil.setContentView(this, resource) return null

左心房为你撑大大i 提交于 2019-12-19 09:23:15

问题


I started using Android Data binding but without success.I have done everything as proposed in the documentation but when I have to set method value I get null. I am using Android Studio 2.1.2 and I put in gradle

dataBinding {
    enabled = true
}

in layout I do exactly da same put layout and inside I put tag data:

<data>
    <variable name="order" type="com.example.Order"/>
</data>

and in code when I want to have binding variable

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ActivityOrderOnePaneBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_order_one_pane);
binding.setOrder(mOrder);

Binding is null,I don't have compile errors.


回答1:


Since you're overriding setContentView in your Activity, you need to replace:

ActivityOrderOnePaneBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_order_one_pane);

with

ActivityOrderOnePaneBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_order_one_pane, getContentFrame(), false);
setContentView(binding.getRoot());

I had the same problem because I overrode setContentView in my base Activity and that fixed it.

If you overrode setContentView, getContentFrame() is the ViewGroup that contains your content, exclusive of the AppBarLayout and Toolbar. Here's an example of what getContentFrame() would look like if you had a base layout similar to what's below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        ...>
        <android.support.design.widget.CollapsingToolbarLayout
           ...>
                <android.support.v7.widget.Toolbar
                   .../>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.ContentFrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v7.widget.ContentFrameLayout>
</android.support.design.widget.CoordinatorLayout>

getContentFrame() just returns the FrameLayout in the above layout.

protected ViewGroup getContentFrame() {
    return (ViewGroup) findViewById(R.id.content_frame);
}

I hope this helps.




回答2:


Try to rebuild gradle and clean project



来源:https://stackoverflow.com/questions/38892346/databindingutil-setcontentviewthis-resource-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!