Android layout dialog.show()使我的应用程序崩溃,为什么?

Android layout dialog.show()使我的应用程序崩溃,为什么?,android-layout,Android Layout,我是阿德里德的新手。 我喜欢在颜色达到一定值时做一些事情。我喜欢(例如)在r大于30时显示警报,但应用程序会崩溃。谢谢你的简单回答 public class MainActivity extends Activity { private AlertDialog dialog; private AlertDialog.Builder builder; private BackgroundColors view; public class BackgroundColors extends

我是阿德里德的新手。 我喜欢在颜色达到一定值时做一些事情。我喜欢(例如)在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); 
} 
运行时在该循环中为true。无法显示对话框吗

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(); 
} 
} 

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

并在线程中发送消息:

handler.sendEmptyMessage(1);
handler.sendEmptyMessage(1);