編輯:初級開發
調用Handler.post(Runnable r)方法,Runnable運行在UI所在線程,所以可以直接調用VIEw.invalidate()
1 package com.Test.androidtest;
2
3 import android.app.Activity;
4 import android.content.Context;
5 import android.graphics.Canvas;
6 import android.graphics.Color;
7 import android.graphics.Paint;
8 import android.os.Bundle;
9 import android.os.Handler;
10 import android.view.VIEw;
11
12 public class TestHandler extends Activity {
13 private MyView myVIEw;
14 private Handler mHandler;
15 public void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 myView = new MyVIEw(this);
18 mHandler = new Handler();
19 mHandler.post(new Runnable(){
20 @Override
21 public void run() {
22 myVIEw.invalidate();
23 mHandler.postDelayed(this, 5);
24 }
25 });
26 setContentView(myVIEw);
27 }
28
29 class MyView extends VIEw{
30 private float x = 0f;
31 public MyVIEw(Context context) {
32 super(context);
33
34 }
35 protected void onDraw(Canvas canvas) {
36 super.onDraw(canvas);
37 x+=1;
38 Paint mPaint = new Paint();
39 mPaint.setColor(Color.BLUE);
40 canvas.drawRect(x, 40, x+40, 80, mPaint);
41 }
42
43 }
44 }
45
在新線程裡更新UI,可以直接postInvalidate()
1 public void onCreate(Bundle savedInstanceState) {
2 super.onCreate(savedInstanceState);
3 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
4
5 myView = new MyVIEw(this);
6 this.setContentView(this.myVIEw);
7 new Thread(new myThread()).start();
8 }
9
10 class myThread implements Runnable {
11 public void run() {
12 while (!Thread.currentThread().isInterrupted()) {
13 try {
14 myVIEw.postInvalidate();
15 Thread.sleep(100);
16 } catch (InterruptedException e) {
17 Thread.currentThread().interrupt();
18 }
19 }
20 }
21 }
22
4、點ok後,將在項目的根目錄下生成一個jocky_build.XML文件,事實上是一個ant build文件。打開這個文件,作適當修改<?XML version
本文節選於機械工業出版社推出的《android應用開發揭秘》一書,作者為楊豐盛。本書內容全面,詳細講解了Android框架、android組件、用戶界面開發、游戲開發、
以Windows平台的SDK為例,這裡Android開發網的模擬器配置路徑為 C:\Users\Administrator\.android\avd\2.3.3.avd
1.2.4 範例程式(3):採單純委託方法1.2.4.1 撰寫步驟:Step-1: 建立android專案:Px03。Step-2: 撰寫Activity的子類別:ac