在使用新的数据绑定api时,我发现你无法绑定到"style"属性.编译器抱怨它无法找到样式.但是,如果我只是按原样设置样式,它会发现它很好.例如:
不起作用:
style="@{TextUtils.isEmpty(row.getSubtitle()) ? @style/SubTitle : @style/Title}"
Run Code Online (Sandbox Code Playgroud)
作品:
style="@style/SubTitle"
Run Code Online (Sandbox Code Playgroud)
错误:
错误:任务':app:compileDebugJavaWithJavac'的执行失败.
java.lang.RuntimeException:发现数据绑定错误.****/数据绑定错误****消息:标识符必须具有XML文件中的用户定义类型.SubTitle缺少文件:/〜/ test/app/src/main/res/layout/row.xml loc:48:71 - 48:78****\data binding error****
bwh*_*ite 28
不幸的是,样式不支持数据绑定:https: //code.google.com/p/android-developer-preview/issues/detail?id = 2613
虽然@bwhite是正确的,但您可以做一些解决方法.这取决于你需要有条件地改变什么.例如,如果您想根据条件(我需要这样做)更改字体,您可以通过制作自定义绑定适配器来实现.
换句话说,做这样的事情:
public class FontBindingAdapter {
@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String typefaceName){
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
// You'd probably want to actually use `typefaceName` to determine the font to use
textView.setTypeface(typeface);
}
Run Code Online (Sandbox Code Playgroud)
然后在你的布局中,像这样:
<TextView
app:font="@{some_condition ? @string/typeface_string_name_bold: @string/typeface_string_name_bold_light}"
Run Code Online (Sandbox Code Playgroud)
我在我的代码中使用了这个,基于一篇很棒的帖子:https://plus.google.com/+LisaWrayZeitouni/posts/LTr5tX5M9mb
| 归档时间: |
|
| 查看次数: |
8889 次 |
| 最近记录: |