我正在进行一场2D游戏,我试图在我绘制的地方制作视图并更新所有内容,告诉包含它的活动游戏结束并在屏幕上显示弹出窗口。问题是我不知道如何从视图中访问活动中的方法,因为它们在不同的线程上工作。
代码看起来或多或少像这样,我想从视图类访问方法displayFrame()。实际代码中的方法对其他textViews等执行更多操作,只有活动才能访问。
public class MainActivity extends Activity{
private MyView myView;
RelativeLayout finalFrame;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this.getApplicationContext());
this.setContentView(myView);
finalFrame = (RelativeLayout) findViewById(R.id.framefinal);
}
private void displayFrame(){
this.finalFrame.setVisibility(View.VISIBLE);
}
}
public class MyView extends SurfaceView implements SurfaceHolder.Callback{
private MyThread myThread;
private boolean finished = false;
public MyView(Context context) {
super(context);
getHolder().addCallback(this);
this.myThread = new MyThread(getHolder(), this);
this.myThread.setRunning(true);
}
public void update() {
this.finished = someMethod();
if(this.finished){
MainActivity.displayFrame();
}
}
public void draw(Canvas canvas){
//draw something
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
public class MyThread extends Thread{
private MyView myView;
private SurfaceHolder surfaceHolder;
private boolean running = false;
private static Canvas canvas;
public MyThread(SurfaceHolder surfaceHolder, MyView myView){
super();
this.surfaceHolder = surfaceHolder;
this.myView = myView;
}
@Override
public void run(){
while(running){
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.myView.update();
this.myView.draw(canvas);
}
} catch (Exception e) {e.printStackTrace();}
finally{
if(canvas!=null)
{
try {
surfaceHolder.unlockCanvasAndPost(canvas);
}
catch(Exception e){e.printStackTrace();}
}
}
}
}
public void setRunning(boolean running){
this.running = running;
}
}
答案 0 :(得分:1)
最简单的方法是在视图中定义一个侦听器接口,并使活动实现它。然后,您可以通知活动游戏已结束并执行相应的逻辑。
{{1}}
答案 1 :(得分:0)
public class MyView extends SurfaceView implements SurfaceHolder.Callback{
private MyThread myThread;
private boolean finished = false;
private Context context;
public MyView(Context context) {
super(context);
this.context=context;
getHolder().addCallback(this);
this.myThread = new MyThread(getHolder(), this);
this.myThread.setRunning(true);
}
runOnUiThread(new Runnable(){
@Override
public void run(){
update();
}
});
public void update() {
this.finished = someMethod();
if(this.finished){
MainActivity mainActivity = (MainActivity) context;
mainActivity.displayFrame();
}
}
public void draw(Canvas canvas){
//draw something
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
你能试试吗