Databingding之坑

本文列举了在使用Android Data Binding过程中可能遇到的一些错误,包括visibility的错误设置、未引用View、忘记在代码中进行数据绑定、直接在表达式中引用View、在include布局中传递变量以及XML中拼接字符串的问题,并提供了相应的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.visibility的使用错误

<ProgressBar
                    android:layout_width="0dp"
                    android:layout_height="25dp"
                    android:layout_weight="1"
                    android:layout_gravity="center"
                    android:visibility="@{!viewModel.isLoaded.get}"/>

其中的

android:visibility="@{!viewModel.isLoaded.get}"应该修改为

android:visibility="@{!viewModel.isLoaded.get ? View.VISIBLE : View.GONE}"

 

2.使用view而未引用view

添加一行import,引入View进来:

 

3.xml中data标签只是绑定model的声名,切记要在代码中进行数据绑定:

首先在xml内

然后是在代码内设置数据进行数据绑定

 

4.可以在表达式中直接引用带 id 的 view,引用时采用驼峰命名法。

<TextView
    android:id="@+id/first_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@={user.firstName}" />

<TextView
    android:text="@{user.lastName}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="@{firstName.getVisibility() == View.GONE ? View.GONE : View.VISIBLE}" />
    <!-- 这里TextView直接引用第一次TextView,firstName为id 的驼峰命名 -->
 

5.在使用应用命名空间的布局中,变量可以传递到任何 include 布局中,并有两种方法

分别是bind和app

在include内

在include的引用文件中接收

 

6.在xml中使用DataBinding拼接字符串时,直接用中文拼接 

报错:

Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’. 
android.databinding.tool.util.LoggedErrorException: failure, see logs for details. 
Exception while handling step android.databinding.annotationprocessor.ProcessExpressions@7cf285d5 javax.xml.bind.UnmarshalException- with linked exception: 
[org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8 sequence.] 
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:333) 
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:563) 
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:249) 
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214) 
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157) 
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:204) 
at android.databinding.tool.store.ResourceBundle


只需要将中文写在string.xml中,从string.xml中获取中文来拼接就行!!!(注:只要不是直接用中文拼接就行,其他方式如将中文写成变量引入,也是可以的!!!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值