You need to enable JavaScript to run this app. Android用Data Binding给include布局传Drawable报mysrc属性未找到错误
优惠活动
大模型
产品
解决方案
定价
更多

Android用Data Binding给include布局传Drawable报mysrc属性未找到错误

报错的核心原因

两个DataBinding的基础规则没踩中,直接触发AAPT校验报错:

  • 作为父布局的activity_main.xml本身没有走DataBinding编译流程,只是普通XML布局
  • 要传参的include标签没设有效id,系统建立不了父布局和被引入子布局之间的绑定桥接
一步步修正的操作

1. 把父布局改成合法的DataBinding结构

DataBinding只会解析被<layout>根节点包裹的XML里的绑定语法,你现在的activity_main.xml根节点是普通RelativeLayout,系统会把include上写的app:mysrc当成普通自定义View属性去系统资源池搜,搜不到自然报attr不存在。
修正后的activity_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- 空的data块占位即可,不需要额外定义变量 -->
    <data>
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:id="@+id/mainlayout">
        
        <!-- include必须设置非空id,属性名和子布局定义的variable完全一致 -->
        <include
            android:id="@+id/include_action_btn"
            layout="@layout/action_bar_button"
            app:mysrc="@{@drawable/notification}"/>

    </RelativeLayout>
</layout>

2. 避坑提醒

  • 别把绑定属性写成android:mysrc:android命名空间下全是系统预定义的属性,根本没有自定义的mysrc,所有DataBinding传参的自定义属性都要走app:也就是res-auto命名空间
  • include的id不能省:没id的include,DataBinding不会为它生成对应的绑定代理,就算语法全对,传的Drawable值也送不到子布局里
  • 新版AGP配置适配:如果用的是AGP 7.0以上版本,建议把原来的dataBinding { enabled = true }替换成buildFeatures下的开关,避免版本兼容问题:
android {
    buildFeatures {
        dataBinding true
    }
}
  • 改完代码先跑一次Build -> Clean Project清旧缓存再重新编译:之前的编译缓存会保留未做DataBinding处理的布局结果,不会自动识别新的绑定语法

3. 子布局不用改

你写的action_bar_button.xml里的变量定义、android:src="@{mysrc}"绑定逻辑都是符合规范的,只要父布局改对,编译就能正常识别传入的Drawable资源。


内容的提问来源于stack exchange,提问作者sudoExclamationExclamation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 18:27:04