Load and set asynchronous bitmap

0

Is it possible to load a Bitmap image asynchronously, but set it as an imageview before it's finished?

Thus:

imageView.setImageBitmap(bitmap);
new Thread( ()->{
     //carregar bitmap
}).start();
    
asked by anonymous 04.02.2016 / 20:41

1 answer

1

You can use 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: link

    
04.02.2016 / 21:50