31

ViewA と ViewB の両方に「タイトル」タグを付けたい。しかし、これを入れることはできませんattrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ViewA">
        <attr name="title" format="string" />
    </declare-styleable>
    <declare-styleable name="ViewB">
        <attr name="title" format="string" />
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

エラーのためAttribute "title" has already been defined . 別の質問は、この解決策を示しています。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="title" format="string" />
    <declare-styleable name="ViewB">
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

ただし、その場合、R.styleable.ViewA_titleandR.styleable.ViewB_titleは生成されません。次のコードを使用して AttributeSet から属性を読み取るために必要です。

TypedArray a=getContext().obtainStyledAttributes( as, R.styleable.ViewA);
String title = a.getString(R.styleable.ViewA_title);

どうすればこれを解決できますか?

4

4 に答える 4

49

あなたが投稿したリンクはあなたに正しい答えを与えます。これはあなたがすることを示唆しています:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="title" format="string" />
    <declare-styleable name="ViewA">
        <attr name="title" />
    </declare-styleable>
    <declare-styleable name="ViewB">
        <attr name="title" />
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

現在、R.styleable.ViewA_titleR.styleable.ViewB_titleの両方にアクセスできます。

機会があれば、この回答を読んでください: Link。関連する引用:

最上位の要素または要素の内部で属性を定義できます。複数の場所で attr を使用する場合は、ルート要素に配置します。

于 2013-09-19T06:51:58.903 に答える
3

継承を使用する必要があります

<resources>
    <declare-styleable name="ViewA">
        <attr name="title" format="string" />
    </declare-styleable>

    <declare-styleable name="ViewB" parent="ViewA"> // inherit from ViewA
        <attr name="min" format="integer" />
        <attr name="max" format="integer" />
    </declare-styleable>
</resources>

あなたのJavaコードで

String namespace = "http://schemas.android.com/apk/res/" + getContext().getPackageName();
int title_resource = attrs.getAttributeResourceValue(namespace, "title", 0); 
String title = "";
if(title_resource!=0){
  title = getContext().getString(title_resource);
}

int min = attrs.getAttributeResourceValue(namespace, "min", 0); // read int value
int max = attrs.getAttributeResourceValue(namespace, "max", 0);
于 2013-09-16T12:27:36.733 に答える