|
本人接触Android没几天,呵呵,这里有个问题请教各位大大
貌似SurfaceView内无法使用自带控件,于是我想在SurfaceView里实现自定义控件
那么实现每个控件的OnTouchEvent方法
初步想法是GameView继承SurfaceView类
用一个数组储存当前GameView内需要OnTouchEvent的自定义控件列表
在GameView中定义OnTouch函数来检查当前事件点与List内的监听区域的关系并激发满足条件的控件的OnTouch函数
当Activity的OnTouchEvent被激发时,调用OnTouch,传递MotionEvent;
模拟时提示意外停止
代码如下:
public class main extends Activity {
/** Called when the activity is first created. */
GameView myView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new GameView(this);
setContentView(myView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
myView.OnTouch(event);
return super.onTouchEvent(event);
}
}
[/code]
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
EventList onTouch;
SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
this.setFocusable(true);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void OnTouch(MotionEvent event){
for(int i = 0;i<onTouch.CONST_MAX;i++){
if(onTouch.rectList==null) continue;
if(onTouch.rectList.contains((int)event.getX(), (int)event.getY())){
onTouch.toolList.onTouch(event);
}
}
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawText("X:"+(int)event.getX()+" Y:"+(int)event.getY(), 50, 50, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
}
private abstract class Tool{
public abstract void onTouch(MotionEvent event);
}
private class EventList{
final int CONST_MAX = 20;
Rect rectList[];
Tool toolList[];
public int add(Rect rect, Tool tool){
int i;
for (i = 0;i<CONST_MAX;i++){
if (rectList==null) {
rectList = rect;
toolList = tool;
break;
}
}
if (i<CONST_MAX)
return i;
else
return -1;
}
public void delete(int which){
rectList[which] = null;
}
}
}
[/code] |
|