自定义视图的 attrs.xml 中的同名属性 [英] Same-named attributes in attrs.xml for custom view

查看:32
本文介绍了自定义视图的 attrs.xml 中的同名属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些共享一些同名属性的自定义视图.在 attrs.xml 中各自的 <declare-styleable> 部分中,我想对属性使用相同的名称:

I'm writing a few custom views which share some same-named attributes. In their respective <declare-styleable> section in attrs.xml I'd like to use the same names for attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView1">
        <attr name="myattr1" format="string" />
        <attr name="myattr2" format="dimension" />
        ...
    </declare-styleable>

    <declare-styleable name="MyView2">
        <attr name="myattr1" format="string" />
        <attr name="myattr2" format="dimension" />
        ...
    </declare-styleable>
</resources>

我收到一个错误消息,指出 myattr1myattr2 已经定义.我发现我应该在 MyView2 中省略 myattr1myattr2format 属性,但如果我这样做,我在控制台中收到以下错误:

I'm getting an error saying that myattr1 and myattr2 are already defined. I found that I should omit the format attribute for myattr1 and myattr2 in MyView2, but if I do that, I obtain the following error in the console:

[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute 

有什么方法可以做到这一点,也许是某种命名空间(只是猜测)?

Is there a way I could accomplish this, maybe some sort of namespacing (just guessing)?

推荐答案

解决方案: 只需从两个视图中提取公共属性,并将它们直接添加为 节点:

Solution: Simply extract common attributes from both views and add them directly as children of the <resources> node:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myattr1" format="string" />
    <attr name="myattr2" format="dimension" />

    <declare-styleable name="MyView1">
        <attr name="myattr1" />
        <attr name="myattr2" />
        ...
    </declare-styleable>

    <declare-styleable name="MyView2">
        <attr name="myattr1" />
        <attr name="myattr2" />
        ...
    </declare-styleable>
</resources>

这篇关于自定义视图的 attrs.xml 中的同名属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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