首页 > 解决方案 > 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()
        }
    }

标签: androidkotlin

解决方案


我不知道为什么文档引用 [your_package_name]。

代替

xmlns:custom="http://schemas.android.com/apk/com.arniesoundboard"

xmlns:custom="http://schemas.android.com/apk/res-auto"

推荐阅读