Android Studio中我的自定义视图找不到自定义属性

3

我正在尝试在Android Studio中为我的自定义视图声明自定义视图,但是Android Studio一直显示这个错误。

AAPT: error: attribute bubbleSize (aka com.first.myapplication:bubbleSize) not found.

这是我的代码:

这是我的自定义视图,只包括声明:

package com.first.myapplication

import android.content.Context
import android.view.View

class Bubble(context: Context): View(context) {

}

我定义自定义属性的attr.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="Bubble">
        <attr name="bubbleSize" format="enum">
            <enum name="small" value="10"/>
            <enum name="big" value="25"/>
        </attr>
    </declare-styleable>
</resources>

我在使用自定义视图和自定义属性的activity_main布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.first.myapplication.Bubble
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:bubbleSize="small"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

你尝试过清除缓存并重启吗? - Shalu T D
@ShaluTD 我试了很多次,还是不行。 - ameencarpenter
请现在尝试我的答案。 - Shalu T D
1个回答

1
请将您的attr.xml文件从xml文件夹移动到res->values文件夹,并按以下方式更改XML
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="Bubble">
        <attr name="bubbleSize" format="enum">
            <enum name="small" value="0"/>
            <enum name="big" value="1"/>
        </attr>
    </declare-styleable>
</resources>

它对我来说运行得很好。你把attr.xml文件放在哪里了? - Shalu T D
在 res/xml 文件夹里,它不应该在这里吗? - ameencarpenter
1
不,它应该在res->values文件夹中。试一下看看是否有效,我会更新我的答案。 - Shalu T D
我已经完成了。再次感谢。 - ameencarpenter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接