Search code examples
androidremoteview

Load Images from Assets in Widget remoteView


I am using the following code to load my image into Android widget ImageView:

remoteViews.setImageViewResource(R.id.widget_image, R.drawable.image);

I have to save the image in drawable folder. Is it possible to save the image in assets instead and load it to remoteView?


Solution

  • Using BitmapFactory, you can load an image in assets/ as a Bitmap from an InputStream provided by AssetManager, and then use the RemoteViews#setImageViewBitmap() method to set it on your widget.

    For example:

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
    ...
    
    try {
        InputStream is = context.getAssets().open("image.jpg");
        Bitmap bmp = BitmapFactory.decodeStream(is);
    
        remoteViews.setImageViewBitmap(R.id.widget_image, bmp);
    }
    catch (IOException e) {
        e.printStackTrace();
    }