本文介绍了活套。prepare()与AlertDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入一个游戏内的时间计数器。如果时间为0时,将有一个AlertDialog它告诉用户的时间出来,又回到了previous活动。下面是该方法(它是扩展了SurfaceView类中):

I would like to insert a time counter inside a game. If the time is 0, there would be an AlertDialog which tells the user the time is out, and goes back to the previous Activity. Here is the method (it is inside a class which extends a SurfaceView):

public void showTime(){
    time--;
    Log.i("GameView time", "" + time);
    if (time <= 0){
        Log.i("gameview time","time out");
        gameTimer.setRunning(false);
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this.getContext());
        AlertDialog alert = alt_bld.create();
        alert.setTitle("Time is out. You lose.");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                main.onBackPressed();
            }});
        alert.show();
    }
}

该GameTimer类是主题:

The GameTimer class is a Thread:

public class GameTimer extends Thread{

private GameView gameView;
private boolean run;

public GameTimer(GameView gameView){
    this.gameView = gameView;
}

public void setRunning(boolean value){
    this.run = value;
}

public void run(){
             Looper.prepare();
    while (run){
        try {
            gameView.showTime();
            sleep(1000);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
            Looper.loop();
}

}

在AlertDialog出现,但应用程序崩溃,与消息:只有创建视图层次可以触摸的意见原来的线程。但是,这是一个创建...线程在哪里的问题?

The AlertDialog appears, but the app crashes, with the message: Only the original thread that created a view hierarchy can touch views. But this is the thread which created... Where's the problem?

推荐答案

为此,使用处理程序或使用

Do this using Handler or Use

this.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub

        }
    });

错误本身道出了原委。
而如果你是不是在活动/视图的父类,然后用一些回调Mechnasim。
这将帮助你解决你的问题。
干杯。

The error itself tells the whole story.And if you are not in Activity/ View's Parent class then use some callback Mechnasim.This will help you to resolve your issue.Cheers.

这篇关于活套。prepare()与AlertDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:31