3

カスタム ウィジェットのカスタム属性の値をプログラムで取得しようとしています。

ウィジェットは LinearLayout を拡張します。カスタム属性を次のように定義しました。

<declare-styleable name="CustomWidget">
    <attr name="customProperty" format="string" />
</declare-styleable>

現在、次のように「customProperty」の値にアクセスしようとしています。

public CustomWidget(Context context, IAttributeSet attrs)
    : base(context, attrs)
{
    var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CustomWidget);
    var s = a.GetString(Resource.Styleable.CustomWidget_customProperty);
}

OnFinishInflate() メソッドでもこのコードを呼び出してみましたが、うまくいきませんでした。

このウィジェットは、それが使用されているものとは別の Android ライブラリ プロジェクトにあることに言及する価値があるでしょう。

4

1 に答える 1

2

私はこれをMonoDroid.ActionBarでうまく動作させています。したがって、カスタム アトリビュートを使用しようとすると、落とし穴に陥る可能性があります。XML で xmlns 名前空間を宣言し、それをアプリケーションの正しい名前空間に参照することを忘れないでください。

したがって、名前空間がどこかにMy.Awesome.App含まれているとしましょう。レイアウトは次のようになります。CustomWidgetaxml

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cs="http://schemas.android.com/apk/res/my.awesome.app"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <my.awesome.app.CustomWidget
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        cs:customProperty="Awesome!"
        />
</LinearLayout>

csxmlns 名前空間が宣言されていることに注意してください。これは、文字列をカスタム レイアウトに渡すためにのCustomWidget宣言で使用されます。axmlAwesome!

customPropertyこれで、のコンストラクターでを取得できるはずですCustomWidget

//Custom Attributes (defined in Attrs.xml)
var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CustomWidget);

var awesomeProperty = a.GetString(Resource.Styleable.CustomWidget_customProperty);
if (null != awesomeProperty)
    //do something with it...

//Don't forget to recycle it
a.Recycle();
于 2013-01-18T11:51:04.567 に答える