android - 在 android studio 中找不到我的自定义 View 的自定义属性

标签 android xml android-studio android-layout android-custom-view

我正在尝试在 android studio 中为我的自定义 View 声明自定义 View 。但是android studio一直向我显示这个错误

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

这是我的代码:

我的自定义 View ,只是声明:

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>

我使用自定义 View 和自定义属性的 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>

最佳答案

请将您的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>

关于android - 在 android studio 中找不到我的自定义 View 的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62773775/

相关文章:

android - Facebook受众群体网络:“预计”支出未显示在“版式”部分中

android - 我可以在我的 Android 工作室的项目资源管理器中隐藏某些文件和文件夹吗?

Android操作栏不可见

java - MPAndroidChart 折线图资源 Null

android - GCM 重复消息

XMLNS 属性声明

c# - 如何获取 XML 属性的值?

android - 不测试时如何从 Gradle 构建中排除 AndroidTest/assets?

android - viewholder 应该持有对适配器的引用吗?

php - 使用 PHP 添加 XML 节点