0

嗨,我正在尝试构建一个布局,其中每 2 秒会弹出一些形状。如果用户单击这些形状之一,它们必须消失。

这样做的正确方法是什么?我想了一个线程,但我错过了。这是我目前的代码(不工作):

public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         l = new LinearLayout(this);
         setContentView(l);

     int counter = 1;
     View v = new CustomDrawableView(this,20,50);

     l.addView(v);

     Thread t = new Thread() {
          public void run() {


                  while (true) {
                        Log.i("THREAD","INSIDE");
                        View h = new CustomDrawableView(c,
                        (int)Math.round(Math.random()*100),

                        (int)Math.round(Math.random()*100));
                        SystemClock.sleep(2000);
                        l.addView(h);
                   }
              }
         };
         t.start();
    }
4

1 回答 1

1

您不能在单独的线程中操作屏幕。您应该使用处理程序,因为它会在 UI 线程上调用。

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    l = new LinearLayout(this);
    setContentView(l);

    int counter = 1;
    View v = new CustomDrawableView(this,20,50);

    l.addView(v);

    ShapeHandler handler = new ShapeHandler();
    handler.sendEmptyMessage(0);
}

private class ShapeHandler extends Handler
{
    @Override
    public void handleMessage(Message msg)
    {
        View h = new CustomDrawableView(c,
            (int)Math.round(Math.random()*100),
            (int)Math.round(Math.random()*100));
        l.addView(h);
        this.sendEmptyMessageDelayed(0, 2000);
    }
}
于 2010-03-17T15:23:25.597 回答