Android DataBinding - 视图上的视图标记不正确:null

时间:2016-05-07 02:28:31

标签: android data-binding

我的类扩展了LinearLayout,我使用DataBinding来扩展布局。但是代码抛出了一个异常,即视图上的视图标记不正确:null。

这是我的代码:

public class DietListView extends LinearLayout {
    private LayoutDietListViewBinding mBinding;
    private List<?> mDietList = new LinkedList<>();
    private LayoutInflater mInflater;

    public DietListView(Context context) {
        this(context,null);
    }

    public DietListView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DietListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mInflater = LayoutInflater.from(context);
        mBinding = DataBindingUtil.inflate(mInflater, R.layout.layout_diet_list_view, null, false);
        addView(mBinding.getRoot());

     }

}

布局文件是:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>

</data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        .....

    </LinearLayout>
</layout>

3 个答案:

答案 0 :(得分:3)

有一个与此相关的错误。在通货膨胀期间进行数据绑定时,数据绑定框架会让人感到困惑。尝试推迟通胀直到数据绑定框架完成后才能查看它是否有效。该bug应该在android gradle插件2.2(Android Studio 2.2)中修复,但在I / O 2016预览中不可用。

https://code.google.com/p/android/issues/detail?id=204890

答案 1 :(得分:2)

这可能不是最好的方法(它更像是一种解决方法),但我所做的是添加isInEditMode()方法,给我的布局充气并立即退出,如下所示:

LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
if(isInEditMode()){
            inflater.inflate(R.layout.your_layout, this);
            return;
        }

在此之后,您可以绑定视图而不会丢失预览功能。

答案 2 :(得分:0)

上面的答案很有帮助,目前我正在像这样使用它,并且它在预览中成功显示,没有错误,并且在运行时效果很好:

if (isInEditMode) {
    LayoutInflater.from(context).inflate(R.layout.layout_keyboard, this, true)
} else {
    binding = LayoutKeyboardBinding.inflate(LayoutInflater.from(context), this, true)
}

请阅读isInEditMode是什么:Android dev docs

相关问题