45

これに対する「類似した」質問と回答が散在しているようです。これらはすべて、からカスタム属性を取得する方法を示していますAttributeSet。これまで私が見つけられなかったのは、android:名前空間タグを取得する方法です。

    <com.custom.view.StatusThumbnail
        android:id="@+id/statusThumbnailContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"/>

layout_heightこのカスタムコンポーネントから属性をプルバックしたいと思います。残念ながら、私がこれを行う方法に最も近いものを読んだことから、次のようになります。

public StatusThumbnail(Context context, AttributeSet attrs) {
    super(context, attrs);

    String height = attrs.getAttributeValue("android", "layout_height");

しかし、これはを返しますnull

確かに、これは珍しいことではありませんか?

4

2 に答える 2

66

名前空間は" http://schemas.android.com/apk/res/android"である必要がありますandroidはxmlファイルで宣言されたエイリアスです

于 2011-10-24T14:53:57.427 に答える
-4

まず、必要な属性を次のように宣言します。

res \ attrs.xml

    <declare-styleable name="StatusThumbnail">
        <attr name="statusThumbnailattr" format="string"/>
    </declare-styleable>

次に、XMLレイアウト宣言で同じ属性を使用します

<com.custom.view.StatusThumbnail
        android:id="@+id/statusThumbnailContainer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        statusThumbnailattr="some value"
        android:layout_weight="1"/>

を使用してアクセスする

public StatusThumbnail(Context context, AttributeSet attrs) {
    super(context, attrs);
TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.StatusThumbnail);
this.mdColorDialogTitle=a.getString(R.styleable.StatusThumbnail_statusThumbnailattr);
}
于 2011-10-24T15:02:35.150 に答える