1

私のカスタムウィジェットのためにプログラムで(コードで)参照されたxmlレイアウトを取得する方法を知っている人はいますか。目的の属性を使用してカスタムの宣言スタイル可能オブジェクトを既に作成しており、文字列や整数などの他の xml 属性値を取得する方法を知っています。

私がやりたいことは次のようなものです:

<MyCustomView
    xmlns:my="http://schemas.android.com/apk/res-auto"
    id="@+id/view"
    my:headerLayout="@layout/my_fancy_layout"
    />

そこで、プログラムで my_fancy_layout を取得し、MyCustomView のコードでそのレイアウトを膨らませたいと考えています。

それを行う方法はありますか?

編集:リソースIDを取得できると思います

int resId = attrs.getAttributeResourceValue(androidns, "headerLayout", 0);

しかし、MyCustomView がライブラリ プロジェクトであり、使用したい場合、正しい名前空間は何ですか?

xmlns:my="http://schemas.android.com/apk/res-auto"

4

2 に答える 2

0

実際、カスタム ビューのコンストラクターでレイアウトを膨らませることができます。

public class MyCustomView extends /* LinearLayout, RelativeLayout, etc. */ {
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }
    public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context, attrs);
    }
    protected void initView(Context context, attrs) {
        LayoutInflater.from(context).inflate(attrs.getAttributeResourceValue("http://schemas.android.com/apk/res-auto", "headerLayout", 0), this, true);
    }
}
于 2013-05-29T11:26:55.810 に答える
0

わかりました、私は自分で解決策を見つけました:

Yout AttributeSet から TypedArray を取得する必要があります。

次のような方法で目的のリソース ID にアクセスできます。

TypedArray attrs = ... ;
int headerRes = attrs.getResourceId(R.styleable.MyCustomWidget_headerLayout, -1);

通常のように膨らませることができるよりも:

LayoutInflater.from(context).inflate(headerRes, this);
于 2013-05-29T12:21:16.457 に答える