views:

219

answers:

1

Hi Hi I'm trying to build a layout where some shapes will popup every 2 seconds. If the user will click one of these shapes, they have to disappear.

What is the correct way of doing this? I thought about a thread, but i missed out. Here's my code at the moment (is not working):

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();
    }
+1  A: 

You can't manipulate the screen in a separate thread. You should use a handler since that gets called on the UI thread.

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);
    }
}
CaseyB
Thanks Casey, I'll try this ASAP.
LucaB
I tried this, but the shape remains the first one and only.I put some log information and I see that the handleMessage() method gets called, but no new shape is draw.I also tried to call l.invalidate() after the l.addView, but with no luck.Any other hint?
LucaB
It's because l is a Linear Layout. Make it a FrameLayout and they should draw like you want.
CaseyB
Worked like a charm, thanks!
LucaB