Pergunta

Existe uma maneira de mostrar a tela "Carregando" com animação no blackberry?

Opções:

  • PME conteúdo de animação
  • multithreading + conjunto de imagens + temporizador / contador
  • padrão api borda
  • alguma outra maneira

Qualquer disso?

Obrigado!

Foi útil?

Solução

Fermin, Anthony +1. Obrigado a todos, você me deu a parte da resposta.
Minha solução final:

1.Criar ou gerar ( livre Ajax carregamento gif gerador ) animação e adicioná-lo ao projeto.

2.Create ResponseCallback de interface (veja Coderholic - Blackberry WebBitmapField ) para receber resultado da execução fio :

public interface ResponseCallback {
    public void callback(String data);  
}

3.Create uma classe para lidar com o seu trabalho discussão de fundo. No meu caso, foi http pedido:

public class HttpConnector 
{
  static public void HttpGetStream(final String fileToGet,
    final ResponseCallback msgs) {
    Thread t = new Thread(new Runnable() {
      public void run() {
        HttpConnection hc = null;
    DataInputStream din = null;
    try {
      hc = (HttpConnection) Connector.open("http://" + fileToGet);
      hc.setRequestMethod(HttpsConnection.GET);
      din = hc.openDataInputStream();
      ByteVector bv = new ByteVector();
      int i = din.read();
      while (-1 != i) {
        bv.addElement((byte) i);
        i = din.read();
      }
      final String response = new String(bv.toArray(), "UTF-8");
      UiApplication.getUiApplication().invokeLater(
        new Runnable() {
          public void run() {
        msgs.callback(response);
              }
            });
    } 
        catch (final Exception e) {
          UiApplication.getUiApplication().invokeLater(
            new Runnable() {
              public void run() {
                msgs.callback("Exception (" + e.getClass() + "): " 
                  + e.getMessage());
              }
            });
        } 
        finally {
          try {
            din.close();
            din = null;
            hc.close();
            hc = null;
          }
          catch (Exception e) {
          }
        }
      }
    });
  t.start();
  }
}

4.Create Tela de espera (um híbrido de Tela Inteira e AnimatedGIFField com interface de ResponseCallback):

public class WaitScreen extends FullScreen implements ResponseCallback 
{
    StartScreen startScreen;
    private GIFEncodedImage _image;
    private int _currentFrame;
    private int _width, _height, _xPos, _yPos;
    private AnimatorThread _animatorThread;
    public WaitScreen(StartScreen startScreen) {
        super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
        setBackground(
            BackgroundFactory.createSolidTransparentBackground(
                Color.WHITE, 100));
        this.startScreen = startScreen;
        EncodedImage encImg = 
          GIFEncodedImage.getEncodedImageResource("ajax-loader.gif");
        GIFEncodedImage img = (GIFEncodedImage) encImg;

        // Store the image and it's dimensions.
        _image = img;
        _width = img.getWidth();
        _height = img.getHeight();
        _xPos = (Display.getWidth() - _width) >> 1;
        _yPos = (Display.getHeight() - _height) >> 1;
        // Start the animation thread.
        _animatorThread = new AnimatorThread(this);
        _animatorThread.start();
        UiApplication.getUiApplication().pushScreen(this);
    }

    protected void paint(Graphics graphics) {
        super.paint(graphics);
            // Draw the animation frame.
            graphics
              .drawImage(_xPos, _yPos, _image
                .getFrameWidth(_currentFrame), _image
                  .getFrameHeight(_currentFrame), _image,
                _currentFrame, 0, 0);
    }

    protected void onUndisplay() {
        _animatorThread.stop();
    }

    private class AnimatorThread extends Thread {
        private WaitScreen _theField;
        private boolean _keepGoing = true;
        private int _totalFrames, _loopCount, _totalLoops;
        public AnimatorThread(WaitScreen _theScreen) {
            _theField = _theScreen;
            _totalFrames = _image.getFrameCount();
            _totalLoops = _image.getIterations();

        }

        public synchronized void stop() {
            _keepGoing = false;
        }

        public void run() {
            while (_keepGoing) {
                // Invalidate the field so that it is redrawn.
                UiApplication.getUiApplication().invokeAndWait(
                  new Runnable() {
                    public void run() {
                        _theField.invalidate();
                    }
                });
                try {
                  // Sleep for the current frame delay before
                  // the next frame is drawn.
                  sleep(_image.getFrameDelay(_currentFrame) * 10);
                } catch (InterruptedException iex) {
                } // Couldn't sleep.
                // Increment the frame.
                ++_currentFrame;
                if (_currentFrame == _totalFrames) {
                  // Reset back to frame 0 
                  // if we have reached the end.
                  _currentFrame = 0;
                  ++_loopCount;
                  // Check if the animation should continue.
                  if (_loopCount == _totalLoops) {
                    _keepGoing = false;
                  }
                }
            }
        }

    }

    public void callback(String data) {
        startScreen.updateScreen(data);
        UiApplication.getUiApplication().popScreen(this);
    }
}

5.In final, criar tela Iniciar para chamar HttpConnector.HttpGetStream e mostrar Tela de espera:

public class StartScreen extends MainScreen
{
    public RichTextField text;
    WaitScreen msgs;
    public StartScreen() {       
        text = new RichTextField();
        this.add(text);
    }

    protected void makeMenu(Menu menu, int instance) {
        menu.add(runWait);
        super.makeMenu(menu, instance);
    }

    MenuItem runWait = new MenuItem("wait", 1, 1) {
        public void run() {
            UiApplication.getUiApplication().invokeLater(
                new Runnable() {
                    public void run() {
                        getFile();
                    }
            });             
        }
    };

    public void getFile() {
        msgs = new WaitScreen(this);
        HttpConnector.HttpGetStream(
            "stackoverflow.com/faq", msgs);                 
    }

    //you should implement this method to use callback data on the screen.
    public void updateScreen(String data)
    {
        text.setText(data);
    }
}

UPDATE: outra solução naviina. UE: a Web 2.0 / Ajax-estilo carregamento pop-up em um aplicativo nativo BlackBerry

Outras dicas

O padrão básico para este tipo de coisa é:

Tenha um segmento em execução um loop que atualiza uma variável (como o índice de fotograma da imagem animada) e então chama invalidate em um campo que desenha a imagem (e, em seguida, dorme por um período de tempo). O invalidate vai fila repintar do campo.

No método pintura do campo, ler a variável e desenhar o quadro apropriado da imagem.

código Pseudo (não totalmente completa, mas para dar-lhe a idéia):

public class AnimatedImageField extends Field implements Runnable {

   private int currentFrame;
   private Bitmap[] animationFrames;

   public void run() {
     while(true) {
       currentFrame = (currentFrame + 1) % animationFrames.length;
       invalidate();
       Thread.sleep(100);
      }
    }

   protected void paint(Graphics g) {
      g.drawBitmap(0, 0, imageWidth, imageHeight, animationFrames[currentFrame], 0, 0);
    }
  }

Note-se também aqui eu usei um conjunto de mapas de bits, mas EncodedImage permite tratar um GIF animado como um objeto, e inclui métodos para obter quadros específicos.

EDIT: Para completar: Adicione isto a um PopupScreen (como na resposta de Fermin) ou criar seu próprio diálogo, substituindo tela diretamente. O segmento separado é necessário porque a API RIM não é thread-safe: você precisa fazer tudo UI relacionados no segmento de eventos (ou mantendo o bloqueio de eventos, consulte BlackBerry UI de threading - O básico do básico

Este é um código simples para tela de carregamento ....

                HorizontalFieldManager popHF = new HorizontalFieldManager();
                popHF.add(new CustomLabelField("Pls wait..."));
                final PopupScreen waitScreen = new PopupScreen(popHF);
                new Thread()
                {
                    public void run() 
                    {

                        synchronized (UiApplication.getEventLock()) 
                        {
                            UiApplication.getUiApplication().pushScreen(waitScreen);
                        }
                       //Here Some Network Call 

                       synchronized (UiApplication.getEventLock()) 
                        {
                            UiApplication.getUiApplication().popScreen(waitScreen);
                        }
                     }
                 }.start();

Se é apenas uma animação você poderia mostrar um animated GIF em um pop-up e fechá-lo quando a operação de carregamento está completo?

A maneira mais fácil é provavelmente a usar o GaugeField padrão, definindo GaugeField.PERCENT estilo. Isto lhe dará uma barra de progresso. Adicione isto a um PopupScreen e vai sentar-se em cima de seu conteúdo. Algo como ..

private GaugeField _gaugeField;
private PopupScreen _popup;

public ProgressBar() {    
    DialogFieldManager manager = new DialogFieldManager();
    _popup = new PopupScreen(manager);
    _gaugeField = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT);    
    manager.addCustomField(_gaugeField);
}

Então, um método de atualização que irá usar _gaugeField.setValue (newValue); para atualizar a barra de progresso.

I normalmente têm esta chamada a partir de qualquer segmento está fazendo o trabalho (carregamento no seu caso, toda vez que uma operação está completa a barra de progresso é atualizado.

Eu sugiro dar uma olhada neste simples implementação. Eu gostei, mas nunca usei. Pode ser útil para você.

texto do link

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top