SurfaceView如何结合Android UI
SurfaceView提供的是直接访问画布进行绘图的机制,在里面创建Android UI是行不通的,不过游戏中经常会用到Andoird UI,这个就需要两者能够很好地结合使用.
先需要说明的一点,SurfaceView,ListView以及UI统统都继承了View,要结合它们只能在上层进行操作,具体的说不太清楚,我理解的也不是很透彻,贴下代码吧,无代码无真相:
?
package com.ray.bubble;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
public class BubbleExplosion extends Activity {
?
?private FrameLayout frame;
?private MyView myView;
?private TextView text;
?
??? public void onCreate(Bundle savedInstanceState) {
??????? super.onCreate(savedInstanceState);
???????
??????? requestWindowFeature(Window.FEATURE_NO_TITLE);
??????? getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
????????????????????? WindowManager.LayoutParams. FLAG_FULLSCREEN);
???????
??????? frame = new FrameLayout(this);
???????
??????? text = new TextView(this);
??????? text.setTextSize(20);
??????? text.setText("lovehui");
??????? text.setHeight(30);
??????? text.setWidth(100);
???????
???? frame.addView(myView);
???? frame.addView(text);
????
??????? setContentView(frame);
??? }
???
??? class MyView extends SurfaceView implements SurfaceHolder.Callback{
??? ?SurfaceHolder holder;
??? ?
??? ?public MyView(Context context) {
??? ??super(context);
??? ??holder = this.getHolder();//获取holder
??? ??holder.addCallback(this);
??? ?}
??? ?public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
??? ?}
??? ?public void surfaceCreated(SurfaceHolder holder) {
??? ??new Thread(new MyThread()).start();
??? ?}
??? ?public void surfaceDestroyed(SurfaceHolder holder) {
??? ?}
??? ?//内部类的内部类
??? ?class MyThread implements Runnable{
??? ??public void run() {
??? ???Canvas canvas = holder.lockCanvas(null);//获取画布
??? ???Paint mPaint = new Paint();
??? ???mPaint.setColor(Color.BLUE);
??? ???canvas.drawRect(new RectF(40,60,80,80), mPaint);
??? ???holder.unlockCanvasAndPost(canvas);//解锁画布,提交画好的图像
??? ??}
??? ?}
??? }
?
}