XML を使用して Android UI 要素を宣言するにはどうすればよいですか?
ベストアンサー1
Android開発者ガイドには、カスタムコンポーネントの構築。 残念ながら、XML属性に関する議論レイアウト ファイル内でのコントロールの宣言のみをカバーし、クラス初期化内での実際の値の処理はカバーしません。手順は次のとおりです。
1.属性を宣言するvalues\attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="android:text"/>
<attr name="android:textColor"/>
<attr name="extraInformation" format="string" />
</declare-styleable>
</resources>
タグ内で非修飾名が使用されていることに注意してくださいdeclare-styleable
。 のような非標準の Android 属性では、extraInformation
その型を宣言する必要があります。スーパークラスで宣言されたタグは、再宣言しなくてもサブクラスで使用できます。
2. コンストラクタを作成する
初期化に使用するコンストラクターが 2 つあるためAttributeSet
、コンストラクターが呼び出す別の初期化メソッドを作成すると便利です。
private void init(AttributeSet attrs) {
TypedArray a=getContext().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView);
//Use a
Log.i("test",a.getString(
R.styleable.MyCustomView_android_text));
Log.i("test",""+a.getColor(
R.styleable.MyCustomView_android_textColor, Color.BLACK));
Log.i("test",a.getString(
R.styleable.MyCustomView_extraInformation));
//Don't forget this
a.recycle();
}
R.styleable.MyCustomView
は自動生成されるint[]
リソースで、各要素は属性の ID です。属性は、要素名に属性名を追加することで、XML 内の各プロパティに対して生成されます。たとえば、には の属性R.styleable.MyCustomView_android_text
が含まれます。その後、さまざまな関数を使用してから属性を取得できます。属性が XML で定義されていない場合は、が返されます。ただし、戻り値の型がプリミティブの場合は例外で、その場合は 2 番目の引数が返されます。android_text
MyCustomView
TypedArray
get
null
すべての属性を取得する必要がない場合は、この配列を手動で作成することもできます。標準の Android 属性の ID は に含まれておりandroid.R.attr
、このプロジェクトの属性は に含まれていますR.attr
。
int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};
に従って、内の何も使用しないでください。android.R.styleable
このスレッド将来変更される可能性があります。これらの定数をすべて 1 か所で表示できると便利なので、ドキュメントにはまだ記載されています。
3. 次のようなレイアウトファイルで使用します。layout\main.xml
名前空間宣言をxmlns:app="http://schemas.android.com/apk/res-auto"
トップレベルのxml要素に含めます。名前空間は、異なるスキーマが同じ要素名を使用する場合に時々発生する競合を回避する方法を提供します(この記事詳細はURLを参照)。URLは単にスキーマを一意に識別する方法です。実際にそのURLでホストする必要のあるものは何もありません何も行われないように見える場合は、競合を解決する必要がない限り、実際に名前空間プレフィックスを追加する必要がないためです。
<com.mycompany.projectname.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:text="Test text"
android:textColor="#FFFFFF"
app:extraInformation="My extra information"
/>
完全修飾名を使用してカスタム ビューを参照します。
Android ラベルビュー サンプル
完全な例が必要な場合は、Android ラベル ビューのサンプルをご覧ください。
TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
CharSequences=a.getString(R.styleable.LabelView_text);
<declare-styleable name="LabelView">
<attr name="text"format="string"/>
<attr name="textColor"format="color"/>
<attr name="textSize"format="dimension"/>
</declare-styleable>
<com.example.android.apis.view.LabelView
android:background="@drawable/blue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:text="Blue" app:textSize="20dp"/>
これは、名前空間属性を持つ に含まれていますLinearLayout
。xmlns:app="http://schemas.android.com/apk/res-auto"