使用View来实现的荧光灯效果,初始代码借助于书Android应用开发揭密

具体的实现

1.GameView.java

package com.zhai.test;

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

public class GameView extends View {

	int miCount = 0;
	int y = 0;
	Context context;
	int width = 0;
	int height = 0;

	public GameView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public GameView(Context context, int _width, int _height) {
		// this.context= context;
		super(context);
		// TODO Auto-generated constructor stub
		this.context = context;
		this.width = _width;
		this.height = _height;

	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		if (miCount < 100) {
			miCount++;

		} else {
			miCount = 0;
		}
		Paint mPaint = new Paint();
		switch (miCount % 4)

		{
		case 0:
			mPaint.setColor(Color.BLUE);
			break;
		case 1:
			mPaint.setColor(Color.RED);
			break;
		case 2:
			mPaint.setColor(Color.BLACK);
			break;
		case 3:
			mPaint.setColor(Color.YELLOW);
			break;
		default:
			mPaint.setColor(Color.GRAY);
			break;

		}

		canvas.drawRect(0, 0, width, height, mPaint);
		super.onDraw(canvas);
	}

}

2.TestViewActivity.java

package com.zhai.test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class TestViewActivity extends Activity {

	private static final int REFRESH = 0x000001;
	private GameView mGameview = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);

		/*
		 * 实例化化对像
		 */

		this.mGameview = new GameView(this, getWindowManager()
				.getDefaultDisplay().getWidth(), getWindowManager()
				.getDefaultDisplay().getHeight());
		setContentView(mGameview);

		// new Thread
		new Thread(new GameThread()).start();

	}

	Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case TestViewActivity.REFRESH:
				mGameview.invalidate();
				break;
			}
			super.handleMessage(msg);
		}

	};

	class GameThread implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (!Thread.currentThread().isInterrupted()) {
				Message message = new Message();
				message.what = TestViewActivity.REFRESH;

				TestViewActivity.this.myHandler.sendMessage(message);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					Thread.currentThread().interrupt();
					e.printStackTrace();
				}
			}
		}

	}

}

3.最后的效果图