在Android開發中,在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;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new DrawView(this));
-
- }
- private class DrawView extends View {
- Paint vPaint = new Paint();
- private int i = 0;
- public DrawView(Context context) {
- super(context);
-
- }
-
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- 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 程序
- invalidate();
- }
- }
-
- }