Android MY-NOTEBOOK

Saturday, August 27, 2011

カスタムビューの作成(Android custom view)

Androidのカスタムビューを作成するには、View を拡張すればOK。
描画コードは、onDraw() メソッドをオーバライドしてそこに記述する。
Swing の paintComponent() に該当するメソッドと思われる。

作成したカスタムビューは、標準で提供されているビューと同様に、res/layout/ 以下のXMLで指定可能。

カスタムビュークラス

package jp.osima.android.mindmemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


public class MCanvas extends View{

	public MCanvas(Context context,AttributeSet attrs){
		super(context,attrs);
	}

	public void onDraw(Canvas canvas){
		
		// 現在のViewのサイズを得る
		int w = getWidth();
		int h = getHeight();
		
		Paint fill_paint = new Paint();
		fill_paint.setStyle(Paint.Style.FILL);
		fill_paint.setColor(Color.WHITE);
		
		Rect rect=new Rect(0,0,w,h);
		canvas.drawRect(rect, fill_paint);
		
		
		Paint draw_paint = new Paint();
		draw_paint.setStyle(Paint.Style.STROKE);
		draw_paint.setColor(Color.BLACK);

		int space=10;
		Rect rect2=new Rect(0+space,0+space,w-space,h-space);
		canvas.drawRect(rect2, draw_paint);
		
	}
}


gist:1174714

レイアウト指定

res/layout/main.xml などに配置

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

<jp.osima.android.mindmemo.MCanvas
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

</LinearLayout>


gist:1174714

© 2011,2012 Tomoaki Oshima