我创建了自定义布局,其中包含图片和标题。要重复使用此布局,我使用<include>
标记。问题是我甚至无法将字符串文字绑定到包含的布局中。我试图遵循这些instructions,但没有成功。
layout / titlebar.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="title" type="String"/>
<!-- <variable name="imgSrc" type="android.graphics.drawable.Drawable" /> -->
</data>
<LinearLayout ... >
<!-- <ImageView ... android:src="{imgSrc}" /> -->
<TextView ... android:text="@{title, default=DefaultTitle}" />
</LinearLayout>
</layout>
布局/ otherlayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto"
...
>
<!-- bind:imgSrc="@{@drawable/some_image}" -->
<include layout="@layout/titlebar"
bind:title="@{Example}" <---------- does not work
/>
...
</LinearLayout>
在gradle中,我为模块启用了数据绑定:
android {
...
dataBinding {
enabled = true
}
...
}
答案 0 :(得分:4)
根据@CzarMatt答案
修复 layout / otherlayout.xml<div class="form-group">
<input type="text" class="form-control newins" id="coll" placeholder="Collection">
</div>
<div class="form-group">
<select id="len" class="form-control newins" >
<option value="">Length</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
数据绑定需要通过<?xml version="1.0" encoding="utf-8"?>
<!--
layout with bindings has to be wrapped in <layout> tag so {LayoutName}Bindings
class can be auto-generated for binding purposes
xmlns:alias="http://schemas.android.com/apk/res-auto"
creates an "app namespace" for custom attributes
-->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<LinearLayout ... >
<!--
// if this layout is also using title "data variable"
// and we want to use default value if title is null
bind:title='@{title ?? "Settings"}
// passing literal reference into the binding
bind:title="@{@string/settings_constant}"
-->
<include layout="@layout/titlebar"
bind:title='@{"Settings"}'
/>
...
</LinearLayout>
</layout>
设置布局,如@RaviRupareliya建议的那样,否则数据绑定将不起作用:
DataBindingUtil
答案 1 :(得分:1)
来自文档:
变量可以从中传递到包含布局的绑定中 通过使用应用程序命名空间和变量包含布局 属性中的名称
这意味着,以下数据变量必须包含在titlebar
和otherlayout
XML文件中:
<data>
<variable name="title" type="java.lang.String"/>
</data>
并且<include>
看起来像这样:
<include layout="@layout/titlebar"
bind:title="@{title}"/>
有关详细信息,请参阅数据绑定文档:
https://developer.android.com/topic/libraries/data-binding/index.html#includes