2012年2月17日金曜日

カスタムView

サンプルの「Snake」を題材として、アプリ作成の基本をまとめるシリーズです。

第三回目は「カスタムView」です。

カスタムViewとは、TextViewやButtonなどの標準のViewではなく、android.view.Viewを拡張して独自に作成したViewのことです。
「Snake」では、TileViewというカスタムViewを作成しています。

・Viewの属性
例えば、標準のTextViewには、textColorやtextSizeなどの属性が用意されています。
カスタムViewに於いても独自の属性を用意することができます。

属性は、res/values/attrs.xmlで作成します。
「Snake」では、以下ように定義しています。

【attrs.xml】
< ?xml version="1.0" encoding="utf-8"?>
< resources>
< declare-styleable name="TileView">
< attr name="tileSize" format="integer" />
< /declare-styleable>
< /resources>

「declare-styleable name」にはカスタムViewのクラス名を、「attr name」には作成する属性名を、「format」には属性のフォーマット名を設定します。

※属性のフォーマット:integer,float,boolean,string,color,dimension

・レイアウト
「Snake」では、カスタムViewをXMLファイルで、以下のようにレイアウトを定義しています。
レイアウトのSnakeViewは、作成したTitleViewを、更に拡張して定義したカスタムViewです。
つまり、カスタムViewを拡張したカスタムViewとなっています。

【snake_layout.xml】
< FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:snake="http://schemas.android.com/apk/res/com.example.android.snake"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

< com.example.android.snake.SnakeView
android:id="@+id/snake"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
snake:tileSize="12"
/>

< /FrameLayout>

作成した属性に対して、tileSize="12"を設定しています。


例えば、下図は属性値をtileSize="24"に設定した場合です。


・コンストラクタ
カスタムViewをXMLファイルでレイアウトするときのコンストラクタの引数に注意してください。
Context contextとAttributeSet attrsが必要になります。

「Snake」では、以下のように定義しています。

【SnakeView.java】
public SnakeView(Context context, AttributeSet attrs) {
super(context, attrs);
initSnakeView();
}


super(context, attrs)で
親クラスのTileViewへ引き渡しています。

【TileView.java】
public TileView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TileView);
mTileSize = a.getInt(R.styleable.TileView_tileSize, 12);
a.recycle();
}

※R.styleable.TileView -->R.styleable.[declare-styleable name]
※R.styleable.TileView_tileSize -->R.styleable.[declare-styleable name]_[attr name]

obtainStyledAttributes()メソッドによって、TypedArrayインスタンスを作成します。
getInt()メソッドで属性値を取得しています。


属性フォーマットの違いによって、以下のメゾッドなどを利用します。

getInt(int index, int defValue)
getFloat(int index, float defValue)
getBoolean(int index, boolean defValue)
getString(int index)
getColor(int index, int defValue)
getDimensionPixelOffset(int index, int defValue)

0 件のコメント:

コメントを投稿