Android中通过<include>标签向DataBinding布局传递属性时出现AAPT错误的解决方案咨询
嘿,这个问题我做项目的时候也踩过坑!你现在遇到的AAPT错误,核心原因是把DataBinding变量当成了普通XML自定义属性来传递——buttonTitle是你在widget_large_button.xml的<data>标签里声明的DataBinding变量,不是通过attrs.xml定义的XML属性,所以AAPT会找不到这个buttonTitle属性,直接报错。
下面给你两种针对性的解决方案,按需选择:
方案一:用DataBinding命名空间传递变量(推荐,适配你的现有结构)
既然你已经在用DataBinding,这种方法最贴合你的代码逻辑:
确保父布局启用DataBinding
把activity_login.xml的根元素用<layout>标签包裹(如果还没做的话),同时添加DataBinding的命名空间(可以用bind和app区分开,避免混淆):<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/apk/res-auto"> <!-- 你的原有根布局(比如ConstraintLayout) --> <androidx.constraintlayout.widget.ConstraintLayout> <!-- 其他代码 --> <include android:id="@+id/login_button" layout="@layout/widget_large_button" bind:buttonTitle="@string/login" <!-- 这里用bind:替代app: --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> </layout>确认项目开启DataBinding
检查你的app/build.gradle文件,确保已经开启DataBinding支持:android { // 其他配置 buildFeatures { dataBinding true } }这样DataBinding就会识别
bind:buttonTitle是传递给被包含布局的变量,而不是XML属性,AAPT就不会报错了。
方案二:改用自定义XML属性(脱离DataBinding变量传递)
如果你不想依赖DataBinding的变量机制,也可以把buttonTitle改成标准的自定义XML属性:
定义自定义属性
在res/values/attrs.xml中添加如下代码(如果没有这个文件就新建一个):<resources> <declare-styleable name="LargeButton"> <attr name="buttonTitle" format="string"/> </declare-styleable> </resources>修改被包含的布局
去掉widget_large_button.xml中的<data>标签,改用自定义属性获取文本:<androidx.appcompat.widget.AppCompatButton android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="25dp" android:layout_marginEnd="25dp" android:layout_marginBottom="16dp" android:background="@drawable/stripe_backgound_05" android:clickable="false" android:focusable="false" android:letterSpacing="0.5" android:paddingTop="25dp" android:paddingBottom="25dp" android:text="?attr/buttonTitle" <!-- 通过?attr获取自定义属性值 --> android:textAllCaps="true" android:textColor="@color/gainsboro_05" android:textSize="16sp"/>在
中传递属性
这时候你原来的app:buttonTitle="@string/login"写法就可以正常工作了,因为AAPT现在能识别这个自定义属性。
内容的提问来源于stack exchange,提问作者Seb

