Android自定义SoundButton中soundFile始终为null,遗漏了什么?
嘿,我帮你排查下这个问题,soundFile总是null大概率是自定义命名空间配置错误导致的,咱们一步步来解决:
1. 修复XML中的自定义命名空间
你在activity_main.xml里定义的自定义命名空间写错了,正确的命名空间应该是http://schemas.android.com/apk/res-auto,而不是具体的包路径。Android通过这个通用命名空间来自动识别项目中的自定义属性,不用硬编码包名。
修改后的activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:custom="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.arniesoundboard.SoundButton android:text="stop it" custom:soundFile="stop_it.mp3" android:layout_width="100dp" android:layout_height="100dp" /> </LinearLayout>
2. 确认属性获取逻辑(你的代码这里是正确的,可再核对)
你的SoundButton类中获取属性的代码是没问题的:
class SoundButton(context: Context, attrs: AttributeSet) : androidx.appcompat.widget.AppCompatButton(context, attrs) { private var soundFile: String? init { context.theme.obtainStyledAttributes(attrs, R.styleable.SoundButton, 0, 0).apply { soundFile = getString(R.styleable.SoundButton_soundFile) recycle() // 别忘了回收TypedArray,避免内存泄漏 } } }
如果刚修改了attrs.xml,可以尝试Clean Project再Rebuild Project,确保资源文件正确同步,避免自动生成的R.styleable类未更新。
3. 额外检查点(可选)
如果后续要播放音频,记得把stop_it.mp3放在res/raw目录下(没有的话手动创建),不过这和当前soundFile为null的问题无关,只是提前给你提个醒~
按照上面的步骤修改后,再运行项目,soundFile应该就能正确获取到"stop_it.mp3"的值啦!
内容的提问来源于stack exchange,提问作者TedTrippin
相关产品推荐
相关产品推荐

