Pergunta

Olá, estou tentando construir um layout onde algumas formas apareçam a cada 2 segundos. Se o usuário clicará em uma dessas formas, terá que desaparecer.

Qual é a maneira correta de fazer isso? Pensei em um tópico, mas perdi. Aqui está o meu código no momento (não está funcionando):

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();
    }
Foi útil?

Solução

Você não pode manipular a tela em um encadeamento separado. Você deve usar um manipulador, pois isso é chamado no thread da interface do usuário.

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);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top