Priya Singhalが回答したように、Android Studioでは、共通の属性名を独自のスタイル名で定義する必要があります。彼らはもう根元にいることはできません。
ただし、他にも注意すべき点がいくつかあります(そのため、私も回答を追加しています)。
- 一般的なスタイルは、ビューと同じ名前にする必要はありません。(それを指摘してくれたこの答えに感謝します。)
- 親との継承を使用する必要はありません。
例
これは、同じ属性を共有する2つのカスタムビューを持つ最近のプロジェクトで行ったことです。カスタムビューに属性の名前があり、が含まれていない限りformat
、コードから通常どおりアクセスできます。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- common attributes to all custom text based views -->
<declare-styleable name="TextAttributes">
<attr name="text" format="string"/>
<attr name="textSize" format="dimension"/>
<attr name="textColor" format="color"/>
<attr name="gravity">
<flag name="top" value="48" />
<flag name="center" value="17" />
<flag name="bottom" value="80" />
</attr>
</declare-styleable>
<!-- custom text views -->
<declare-styleable name="View1">
<attr name="text"/>
<attr name="textSize"/>
<attr name="textColor"/>
<attr name="gravity"/>
</declare-styleable>
<declare-styleable name="View2">
<attr name="text"/>
<attr name="textSize"/>
<attr name="textColor"/>
<attr name="gravity"/>
</declare-styleable>
</resources>
合理化された例
実際、属性をカスタム名で指定する必要はありません。format
少なくとも1つのカスタムビューに対してそれらを定義する(それらにを与える)限り、どこでも(なしでformat
)それらを使用できます。したがって、これも機能します(そしてきれいに見えます):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="View1">
<attr name="text" format="string"/>
<attr name="textSize" format="dimension"/>
<attr name="textColor" format="color"/>
<attr name="gravity">
<flag name="top" value="48" />
<flag name="center" value="17" />
<flag name="bottom" value="80" />
</attr>
</declare-styleable>
<declare-styleable name="View2">
<attr name="text"/>
<attr name="textSize"/>
<attr name="textColor"/>
<attr name="gravity"/>
</declare-styleable>
</resources>
ただし、大規模なプロジェクトの場合、これは面倒になる可能性があり、単一の場所の上部に定義する方がよい場合があります(ここで推奨されています)。