Android Studio MapActivity添加FloatingActionButton报资源链接失败
资源链接失败问题排查与FAB菜单实现方案
android resources linking failed 报错由多个代码问题共同触发,核心原因是组件、属性、单位不匹配,具体问题和修复方式如下:
- 组件与属性不匹配
你引入的是官方Material组件库的com.google.android.material.floatingactionbutton.FloatingActionButton,但代码中写入的app:fab_addButtonColorNormal、app:fab_title、app:fab_icon、app:fab_colorNoemal、app:fab_colorPressed、app:fab_labelSstyle均为第三方浮动菜单扩展库的自定义属性,原生FAB没有这些属性定义,编译时资源检索找不到对应项就会直接报错。另外原生FAB本身不支持嵌套其他FAB作为子菜单项,你之前写的嵌套结构本身就不符合组件使用规范。 - 属性拼写错误
即便引入对应第三方库,现有属性也存在拼写问题:app:fab_labelSstyle中S大写、app:fab_colorNoemal将Normal错写为Noemal,都会导致属性匹配失败。 - 单位使用错误
边距属性使用了字体专用单位sp,布局间距必须使用dp作为单位,会触发资源校验失败。 - 资源引用缺失
代码中引用的@drawable/icon、@style/custom、@string/todo如果没有在项目对应目录下提前定义,也会直接触发资源链接错误。
可落地实现方案
二选一即可,优先推荐第一种无额外依赖的官方实现方案:
方案1:基于官方Material组件实现展开菜单(推荐)
不需要引入第三方库,直接在布局中放置主按钮+默认隐藏的子按钮,在代码中控制点击后的动画和显隐即可。
首先替换布局中原有错误的FAB代码块,修正所有单位和属性错误:
<!-- 主悬浮按钮 --> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:backgroundTint="#3490dc" android:src="@drawable/ic_add" android:contentDescription="@string/app_name" /> <!-- 子功能按钮 默认隐藏 --> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/fab_main" android:layout_alignEnd="@id/fab_main" android:layout_marginBottom="16dp" android:visibility="gone" android:backgroundTint="@color/white" android:src="@drawable/ic_camera" app:fabSize="mini" android:contentDescription="Camera" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_game" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/fab_camera" android:layout_alignEnd="@id/fab_main" android:layout_marginBottom="16dp" android:visibility="gone" android:backgroundTint="@color/white" android:src="@drawable/ic_game" app:fabSize="mini" android:contentDescription="Game" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_video" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/fab_game" android:layout_alignEnd="@id/fab_main" android:layout_marginBottom="16dp" android:visibility="gone" android:backgroundTint="@color/white" android:src="@drawable/ic_video" app:fabSize="mini" android:contentDescription="Video" />
后续在MapActivity中给主FAB添加点击监听,控制三个子按钮的平移、缩放动画和显隐状态,就能实现点击唤起功能菜单的效果,稳定性远高于老旧第三方库。
方案2:使用第三方FAB菜单库
如果要保留原有自定义属性的写法,需要先在模块级build.gradle中引入对应支持这些属性的FAB菜单依赖,之后修正所有拼写错误的属性名,将所有sp单位替换为dp,补全缺失的图标、样式、字符串资源,重新编译即可。
注意:此类第三方FAB菜单库多数已停止维护,和新版Material库、Android13+系统存在兼容性问题,非必要不推荐使用。
内容的提问来源于stack exchange,提问作者Leyoussi Bonachy Lauriel
相关产品推荐
相关产品推荐

