android - kotlin/android - 空自定义属性
问题描述
我正在阅读本指南以创建我自己的自定义按钮。soundFile
始终为空。我错过了什么?
资源/值/attrs.xml
<resources>
<declare-styleable name="SoundButton">
<attr name="soundFile" format="string" />
</declare-styleable>
</resources>
我的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/com.arniesoundboard"
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>
com.arniesoundboard.SoundBoard
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()
}
}
解决方案
我不知道为什么文档引用 [your_package_name]。
代替
xmlns:custom="http://schemas.android.com/apk/com.arniesoundboard"
和
xmlns:custom="http://schemas.android.com/apk/res-auto"
推荐阅读
- javascript - 使用导航器剪贴板从画布 blob 中存储图像/png
- html - 位置粘性和溢出:隐藏
- python - PHP 中的 Python time.time()
- android-date - 在android studio中显示不同时区的时间
- python - Geoseries 意外转换为 pandas.Series
- php - PHP DateTime::createFromFormat 返回错误的日期
- javascript - javascript中是否有任何方法可以为一个HTML元素单独操作一个函数?
- python - Dash/Plotly Express Arguments to update_layout() 的文档
- routes - 有什么方法可以在 Here Routing Service 中发送有关路由的反馈?
- javascript - 从json转换时如何强制用双引号将csv文件的所有值括起来?