安卓数据绑定(dataBinding)从0到学会使用Android 开发技术分享

databinding view is not a bin

2017-08-01  本文已影响326人  苗校长

好吧其实不是来讲这个的,重点是说可能换一种写法解决,还是把过程写下来吧.
通过几个控件组合了一个自定义view,继承自RelativeLayout,就叫IdCardView吧想用databinding来简化操作,去年怎么写怎么爽,今天忽然就发现了好多坑:
先看怎么初始化的:

  public IDCardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }
    private void initView() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context
                .LAYOUT_INFLATER_SERVICE);
//注意这的container是自己,是否绑定到container上设置为false
        binding = DataBindingUtil.inflate(inflater, R.layout.view_idcard, this, false);
    }

然后很happy的开始跑了起来,发现WTF怎么不显示,记得去年就是这样写的呀,哎当时真的是不求甚解呀...而且记得跟着断点走了一边,最后DataBindingUtils调用了一个factory.inflate(....) 这个factory都是context湖片区的layoutinflator,应该是没问题的,但是这是什么情况呢,算了试试直接用RelativeLayout的inflate方法写一下试试,于是initView()就这样写:


    private void initView() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context
                .LAYOUT_INFLATER_SERVICE);
        View root = inflate(getContext(), R.layout.view_idcard, null);

        binding = DataBindingUtil.bind(root);
       // binding = DataBindingUtil.getBinding(root);
       // binding = DataBindingUtil.findBinding(root);
    }

然后就得到了标题提到的view is not a binding layout root
后边注释掉的是后边的尝试,其中findBinding(root)的含义是

Retrieves the binding responsible for the given View. If view is not a binding layout root, its parents will be searched for the binding. If there is no binding, null will be returned.

意思是说,先从root中找绑定的东东,如果root不是个layout包裹的view,那就让他的父控件找,找不到就返回null;

然后getBinding(root)的意思是

Retrieves the binding responsible for the given View layout root. If there is no binding, null
 will be returned. This uses the DataBindingComponent set in[setDefaultComponent(DataBindingComponent)](https://developer.android.com/reference/android/databinding/DataBindingUtil.html#setDefaultComponent(android.databinding.DataBindingComponent))
.

直接看这个view 是不是layout包裹的view,不是直接返回null

但是这个layout确实是layout标签包裹的,为什么么各种绑定获得的都不是一个binding呢,这是一个问题...我也不知道为什么...build后能够获取binding说明layout文件没有错,也就是说inflate的过程不会错,那就是参数写错了,于是往回看了一下最初写的

 binding = DataBindingUtil.inflate(inflater, R.layout.view_idcard, this, false);

第四个参数是不将绑定到container上,因为写adapter什么的不把inflate到的view填充到container上习惯了就直接写了,但这里的container是自己,如果不绑上去那返回的不就是空了吗,于是还按照最初的写法,将最后一个参数false改为true,就能够显示了,也就不需要bind,getBinding,findbinding了,也算曲线解决了view is not a binding layout root的坑,
最终初始化代码为:

 private void initView() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context
                .LAYOUT_INFLATER_SERVICE);
        DataBindingUtil.inflate(inflater, R.layout.view_idcard, this, false);
    }
上一篇 下一篇

猜你喜欢

热点阅读