mat*_*oni 5 android android-databinding
我创建了包含图像和标题的自定义布局。为了重用这个布局,我使用了<include>标签。问题是我什至无法将字符串文字绑定到所包含的布局中。我试图按照这些 说明进行操作,但没有成功。
布局/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>
Run Code Online (Sandbox Code Playgroud)
布局/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>
Run Code Online (Sandbox Code Playgroud)
在 gradle 中,我为模块启用了数据绑定:
android {
...
dataBinding {
enabled = true
}
...
}
Run Code Online (Sandbox Code Playgroud)
基于@CzarMatt 答案的固定布局/otherlayout.xml
<?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>
Run Code Online (Sandbox Code Playgroud)
数据绑定需要DataBindingUtil按照@RaviRupareliya 的建议设置布局,否则数据绑定将不起作用:
public class OtherActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.otherlayout);
DataBindingUtil.setContentView(this, R.layout.otherlayout);
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3710 次 |
| 最近记录: |