问题描述:
在自定义LinearLayout中使用DataBinding的时候:
1:无法使用setContentView(Activity activity, int layoutId)2:使用inflate(LayoutInflater inflater, int layoutId,@Nullable ViewGroup parent, boolean attachToParent)方法无效。
解决方法:采用:DataBindingUtil.bind()进行绑定。
具体使用:如下,必须在调用bind()之前给view设置一个tag;
注意:此处的tag不能随便乱取,而是要取下图中DataBinderMapper中getLayoutId()方法中与对应布局相匹配的tag值。
TestView1Binding binding;
public TestView1(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.test_view_1,this);
view.setTag("layout/test_view_1_0");
binding=DataBindingUtil.bind(view);
}
ps:如何找到DataBinderMapper文件。可以在如下目录找到。
(也可以:
DataBindingUtil.bind(view)-->DataBindingUtil.bind(View root)
-->DataBindingUtil.bind(View root,DataBindingComponent bindingComponent)
-->DataBinderMapper.getLayoutId(String tag)
-->在getLayoutId(String tag)方法中找到对应的tag值)