1

我是新来的机器人。我喜欢在颜色达到某个值时做事。我喜欢(例如)在 r 大于 30 时显示警报,但应用程序会崩溃。感谢您提供非常简单的答案。

public class MainActivity extends Activity { 
private AlertDialog dialog; 
private AlertDialog.Builder builder; 
private BackgroundColors view; 

public class BackgroundColors extends SurfaceView implements Runnable { 
public int grand=0;
public int step=0;
private boolean flip=true;
private Thread thread; 
private boolean running; 
private SurfaceHolder holder; 

public BackgroundColors(Context context) { 
super(context); 
} 

在此循环内运行时为真。不可能显示对话框??

public void run() { 
 int r = 0; 
while (running){ 
if (holder.getSurface().isValid()){ 
     Canvas canvas = holder.lockCanvas(); 
     if (r > 250) 
      r = 0; 
     r += 10; 

     if (r>30 && flip){
            flip=false;


    //      *********************************
            dialog.show(); 
    //      *********************************
    //      CRASH !!        


       }

     try { 
      Thread.sleep(300); 
     } 
     catch(InterruptedException e) { 
      e.printStackTrace(); 
     } 
     canvas.drawARGB(255, r, 255, 255); 
     holder.unlockCanvasAndPost(canvas); 

   } 
   } 





  } 

  public void start() { 
   running = true; 
   thread = new Thread(this); 
   holder = this.getHolder(); 
   thread.start(); 
  } 

  public void stop() { 
   running = false; 
   boolean retry = true; 
   while (retry){ 
    try { 
         thread.join(); 
         retry = false; 
    } 
    catch(InterruptedException e) { 
         retry = true; 
} 
   } 
  } 

  public boolean onTouchEvent(MotionEvent e){ 
   dialog.show(); 
   return false; 
  } 
  protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
      super.onSizeChanged(xNew, yNew, xOld, yOld);
      grand = xNew;
      step =grand/15;
  }
} 

public void onCreate(Bundle b) { 
  super.onCreate(b); 
  view = new BackgroundColors(this); 
  this.setContentView(view); 
  builder = new AlertDialog.Builder(this); 
  builder.setMessage("ciao");
  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
   public void onClick(DialogInterface dialog, int which) { 
     Log.d("Basic", "It worked"); 
   } 
  }); 
  dialog = builder.create(); 
} 

public void onPause(){ 
  super.onPause(); 
  view.stop(); 
} 

public void onResume(){ 
  super.onResume(); 
  view.start(); 
} 
} 
4

1 回答 1

0

你不能在线程中显示对话框。你应该为此使用处理程序。在主线程中创建一个处理程序并将其发送到你的线程,而不是你的线程中的 dialog.show() 你应该将消息发送到处理程序和 handleMessage 方法处理程序编写 dialog.show()。例子:

Handler handler = new Handler(){ 
@Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case 1:
              dialog.show();
break;
}}};

并在线程中发送消息:

handler.sendEmptyMessage(1);
于 2012-10-24T06:31:42.983 回答