Domanda

Ciao Sto cercando di costruire un layout in cui alcune forme popup ogni 2 secondi. Se l'utente clicca uno di queste forme, devono scompaiono.

Qual è il modo corretto di fare questo? Ho pensato a un filo, ma io perso. Ecco il mio codice al momento (non funziona):

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();
    }
È stato utile?

Soluzione

Non è possibile manipolare lo schermo in un thread separato. È necessario utilizzare un gestore dal momento che viene chiamato sul thread dell'interfaccia utente.

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);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top