12
12

More than 5 years have passed since last update.

attrs.xml に同じ名前・型の属性名を定義したい

Posted at

CustomView を作っていると、独自の xml の属性を定義するためにattrs.xmlを作って、<declare-styleable>でアトリビュートを定義する場面があります。

この時、同じ型で同じ名前の属性を、複数の CustomView にまたがって使い回したい場面で、以下のようにすると、エラーでビルドできません。


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CompoundRelativeLayout">
        <attr name="checked" format="boolean|reference"/>
    </declare-styleable>
    <declare-styleable name="CompoundFrameLayout">
        <attr name="checked" format="boolean|reference"/>
    </declare-styleable>
    <declare-styleable name="CompoundGridLayout">
        <attr name="checked" format="boolean|reference"/>
    </declare-styleable>
    <declare-styleable name="CompoundLinearLayout">
        <attr name="checked" format="boolean|reference"/>
    </declare-styleable>
</resources>

同じ名前・型の属性を複数宣言していることになるため、コンパイルに失敗します。

<attr>タグは、<declare-styleable>タグの子要素としてだけでなく、<resources>タグの子要素としても配置することが出来、<resources>タグの子要素としておくことで、複数の CustomView で共通な名前・型の属性を宣言することになります。


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="checked" format="boolean|reference"/>
    <declare-styleable name="CompoundRelativeLayout">
        <attr name="checked"/>
    </declare-styleable>
    <declare-styleable name="CompoundFrameLayout">
        <attr name="checked"/>
    </declare-styleable>
    <declare-styleable name="CompoundGridLayout">
        <attr name="checked"/>
    </declare-styleable>
    <declare-styleable name="CompoundLinearLayout">
        <attr name="checked"/>
    </declare-styleable>
</resources>

これで無事コンパイルできるようになりました。

12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12