Android自定义属性未显示 [英] Android custom attributes not showing

查看:161
本文介绍了Android自定义属性未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多人想知道如何获取自定义组件的自定义属性的帖子,但这不是我的问题.我已经创建了一个自定义组件,并且尝试添加属性,但是当我在xml文件的顶部添加名称空间时,它只能找到两个随机的自定义属性"paddingEnd"和"paddingStart".

I've seen a lot of posts with people wanting to know how to get custom attributes for a custom component but that is not my question. I have created a custom component and I'm trying to add attributes but when I add the namespace at the top of my xml file it only finds two random custom attributes "paddingEnd" and "paddingStart".

<resources>
    <declare-styleable name="menu_item_attrs">
        <attr name="imageId" format="integer" />
        <attr name="menuText" format="string" />
    </declare-styleable>
</resources>

这是attrs.xml文件.

This is attrs.xml file.

public MenuListItem(Context context, AttributeSet set) {
    super(context, set);

    TypedArray a = context.obtainStyledAttributes(set, R.styleable.menu_item_attrs);
    if (a == null) {
        return;
    }
    CharSequence s = a.getString(R.styleable.menu_item_attrs_menuText);
    if (s != null) {
        // do something
    }
}

这是我的自定义类中的构造函数.

This is the constructor in my custom class.

        <LinearLayout
            xmlns:custom="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/expanding_layout"
            android:background="#029eed">

            <aaron.testappanim.MenuListItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"/>
        </LinearLayout>

这是我正在使用的组件.我想将值添加到"imageId"和"menuText",但它们不可用.唯一显示的是与填充相关的内容,如下所示.

This is my component in use. I want to add values to "imageId" and "menuText" but they aren't available. The only things that show are padding related as shown below.

有什么想法的人吗?

推荐答案

找到了解决方案.

碰巧的是,您需要将可设置样式的名称与您的类名称相同.

As it happens you need to have the styleable name the same as your class name.

<resources>
    <declare-styleable name="MenuListItem">
        <attr name="my_custom_attribute" format="integer" />
    </declare-styleable>
</resources>

在这种情况下,许多关于该主题的帖子都是错误的,因为我可以看到很多样式名称完全不同的情况.

Many many posts on this subject are wrong in that case as I can see plenty with the styles name being completely different.

希望这可以阻止其他人掉入这个陷阱.

Hopefully this can stop someone else falling into this trap.

欢呼

这篇关于Android自定义属性未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆