Load and set bitmap asincrona

Asked

Viewed 39 times

0

It is possible to load a Bitmap image asynchronously, but set it to an imageview before finishing?

Thus :

imageView.setImageBitmap(bitmap);
new Thread( ()->{
     //carregar bitmap
}).start();

1 answer

1


You can use a AsyntTask for this. Try something similar:

class CarregaImagem extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;

    public CarregaImagem(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        //Aqui você carrega a imagem como quiser;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        return BitmapFactory.decodeResource(getResources(), data, options);;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

public void carregaImagem(int resId, ImageView imageView) {
    CarregaImagem task = new CarregaImagem(imageView);
    task.execute(resId);
}

Reference: http://developer.android.com/intl/pt-br/training/displaying-bitmaps/process-bitmap.html

  • Thank you very much, solved beautifully

Browser other questions tagged

You are not signed in. Login or sign up in order to post.