libro
www.tuyano.com
Google androidプログラミング入門

オリジナル・ウィジェットを作ろう! (3/6)

作成:2009-12-28 17:06
更新:2011-04-24 13:06

■ソースコードをチェックする

これで完成です。ここでは、「表示するメッセージ(テキスト)」「メッセージのフォントサイズ」「メッセージの色」「背後に描く図形の色」といった値をフィールドとして保持するようにしてあります。そして、それらの値をもとに楕円とテキストを描画します。

まず、「引数2つのコンストラクタ」から見ましょう。ここでは、第2引数で渡されるAttributeSetから各種の属性の値を取り出し、フィールドに納めています。
String message = attr.getAttributeValue(null, "message");
this.message = message != null ? message : this.message;
this.messageSize = attr.getAttributeIntValue(null, "messageSize", 10);
this.drawColor = attr.getAttributeIntValue(null, "drawColor", Color.RED);
this.messageColor = attr.getAttributeIntValue(null, "messageColor", Color.BLUE);
値の取得は、「getAttributeValue」「getAttributeIntValue」で行っています。これらは、第1引数にパッケージ名、第2引数に属性名(getAttributeIntValueでは第3引数にデフォルトの値)をそれぞれ指定して呼び出します。例えば、getAttributeValue(null, "message")ならば"message"という属性のString値を取り出しますし、getAttributeIntValue(null, "drawColor", Color.RED)ならば"drawColor"という属性のint値を取得します。

もう一つのポイントであるonMeasureでは、引数で渡された値と、別途用意してある縦横幅の値を示すフィールドの値から設定すべき縦横幅を計算し、setMeasuredDimensionで設定をしています。といっても、実はここでは単にフィールドに保管している値を使ってsetMeasuredDimensionをしているだけですが。

※プログラムリストが表示されない場合

AddBlockなどの広告ブロックツールがONになっていると、プログラムリスト等が表示されない場合があります。これらのツールをOFFにしてみてください。

●プログラム・リスト●

public MySimpleView(Context context, 
			AttributeSet attr) {
	super(context, attr);
	String message = attr.getAttributeValue
			(null, "message");
	this.message = message != null ? message : 
			this.message;
	this.messageSize = attr.getAttributeIntValue
			(null, "messageSize", 10);
	this.drawColor = attr.getAttributeIntValue
			(null, "drawColor", Color.RED);
	this.messageColor = attr.getAttributeIntValue
			(null, "messageColor", Color.BLUE);
}
※関連コンテンツ

「Google androidプログラミング入門」に戻る