在開
發中,在activity中關聯視圖view是一般使用setcontentview方法,該方法一種參數是使用xml資源直接創 建:setcontentview
(int layoutresid),指定layout中的一個xml的id即可,這種方法簡單。另一個方法是
setcontentview(android.view.view),參數是指定一個視圖view對象,這種方法可以使用自定義的視圖類。
在一些場合中,需要對view進行一些定制處理,比如擷取到canvas進行圖像繪制,需要重載view::ondraw方法,這時需要對view
進行派生一個類,重載所需要的方法,然後使用setcontentview(android.view.view)與activity進行關聯,具體代碼
舉例如下:
public class temp extends activity {
/** 在activity中關聯視圖view */
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(new drawview(this));
}
/*自定義類*/
private class drawview extends view {
private paint paint;
/**
* constructor
*/
public drawview(context context) {
super(context);
paint = new paint();
// set‘s the paint‘s colour
paint.setcolor(color.green);
// set‘s paint‘s text size
paint.settextsize(25);
// smooth‘s out the edges of what is being drawn
paint.setantialias(true);
}
protected void ondraw(canvas canvas) {
super.ondraw(canvas);
canvas.drawtext("hello world", 5, 30, paint);
// if the view is visible ondraw will be called at some point in the
// future
invalidate();
}
第二個例子,動态繪圖
public class myandroidprojectactivity extends activity {
/** called when the activity is first created. */
/*
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
}*/
static int times = 1;
paint vpaint = new paint();
private int i = 0;
system.out.println("this run " + (times++) +" times!");
// 設定繪圖樣式
vpaint.setcolor( 0xff00ffff ); //畫筆顔色
vpaint.setantialias( true ); //反鋸齒
vpaint.setstyle( paint.style.stroke );
// 繪制一個弧形
canvas.drawarc(new rectf(60, 120, 260, 320), 0, i, true, vpaint );
// 弧形角度
if( (i+=10) > 360 )
i = 0;
// 重繪, 再一次執行ondraw 程式
