カスタム属性の定義 質問する

カスタム属性の定義 質問する

次のように独自の属性を実装する必要がありますcom.android.R.attr

公式ドキュメントには何も見つからなかったので、これらの属性を定義する方法と、コードからそれらを使用する方法についての情報が必要です。

ベストアンサー1

現在、最も優れたドキュメントはソースです。それを見てみて下さい。ここ (attrs.xml)

属性は、最上位<resources>要素または要素内で定義できます<declare-styleable>。属性を複数の場所で使用する場合は、ルート要素に配置します。すべての属性は同じグローバル名前空間を共有することに注意してください。つまり、要素内に新しい属性を作成しても、<declare-styleable>その属性は要素の外部で使用できますが、同じ名前で異なるタイプの別の属性を作成することはできません。

要素<attr>には 2 つの XML 属性nameとがありますformatnameを使用して要素に名前を付けることができ、コード内で参照する方法は次のようになります (例: ) R.attr.my_attributeformat属性は、必要な属性の「タイプ」に応じて異なる値を持つことができます。

  • 参照 - 別のリソース ID を参照する場合 (例: "@color/my_color"、"@layout/my_layout")
  • ブール値
  • 寸法
  • 浮く
  • 整数
  • 分数
  • enum - 通常は暗黙的に定義されます
  • フラグ - 通常は暗黙的に定義される

|たとえば、を使用して、形式を複数のタイプに設定できますformat="reference|color"

enum属性は次のように定義できます。

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag属性は、ビット論理和をとれるように値を定義する必要がある点を除いては同様です。

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

属性に加えて、<declare-styleable>要素があります。これにより、カスタム ビューが使用できる属性を定義できます。これは、 要素を指定して行います。要素<attr>が以前に定義されている場合は、 を指定しませんformat。android:gravity などの android 属性を再利用する場合は、次のように で行うことができますname

カスタムビューの例<declare-styleable>:

<declare-styleable name="MyCustomView">
  <attr name="my_custom_attribute" />
  <attr name="android:gravity" />
</declare-styleable>

カスタム ビューで XML でカスタム属性を定義する場合は、いくつかの作業を行う必要があります。まず、属性を見つけるために名前空間を宣言する必要があります。これは、ルート レイアウト要素で行います。通常は のみですxmlns:android="http://schemas.android.com/apk/res/android"。ここで も追加する必要がありますxmlns:whatever="http://schemas.android.com/apk/res-auto"

例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:whatever="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <org.example.mypackage.MyCustomView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>

最後に、そのカスタム属性にアクセスするには、通常、次のようにカスタム ビューのコンストラクターで実行します。

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);

  String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);

  //do something with str

  a.recycle();
}

終わり。 :)

おすすめ記事