オリジナル・ウィジェットを作ろう! (2/6)
作成:2009-12-28 17:04
更新:2011-04-24 13:05
更新:2011-04-24 13:05
■MySampleViewクラスを作る
では、実際に簡単なサンプルを作ってみましょう。ここでは「MySampleView」というクラスを作成します。jp.tuyanoパッケージ内にMySampleView.javaというソースコードファイルを用意し、以下のように記述をしましょう。
(by. SYODA-Tuyano.)
※プログラムリストが表示されない場合
AddBlockなどの広告ブロックツールがONになっていると、プログラムリスト等が表示されない場合があります。これらのツールをOFFにしてみてください。
●プログラム・リスト●
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | package jp.tuyano; import android.content.Context; import android.graphics.*; import android.util.AttributeSet; import android.view.View; class MySimpleView extends View { private String message = "sample message." ; private float messageSize = 10f; private int drawColor = Color.RED; private int messageColor = Color.BLUE; private int width = 300 ; private int height = 200 ; public String getMessage() { return message; } public void setMessage(String message) { this .message = message; } public float getMessageSize() { return messageSize; } public void setMessageSize( float messageSize) { this .messageSize = messageSize; } public int getDrawColor() { return drawColor; } public void setDrawColor( int drawColor) { this .drawColor = drawColor; } public int getMessageColor() { return messageColor; } public void setMessageColor( int messageColor) { this .messageColor = messageColor; } public int getW() { return width; } public void setW( int width) { this .width = width; } public int getH() { return height; } public void setH( int height) { this .height = height; } public MySimpleView(Context context) { super (context); } 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); } @Override public void onDraw(Canvas c) { c.drawColor(Color.WHITE); Paint fill_paint = new Paint(); fill_paint.setStyle(Paint.Style.FILL); fill_paint.setColor( this .drawColor); c.drawOval( new RectF(0f, 0f, this .width, this .height), fill_paint); fill_paint.setColor( this .messageColor); fill_paint.setTextSize( this .messageSize); c.drawText( this .message, 5f, this .messageSize + 5 , fill_paint); } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(width, height); } } |
※関連コンテンツ