Matt Sevrens
Matt Sevrens

Reputation: 121

Draw on Canvas to Home Screen Widget - Android

I'm trying to create a home screen widget that's a custom way to display time (Imagine an arc clock but different). So, I need to be able to draw using the android graphics library to this widget. Realistically I'd only need to update every 20 or 30 minutes.

Whats the best way to do this? It seems like there's a lot of limitations on types of views for widgets. Can I just include a canvas which I update with info and it will redraw? Or would I need perhaps it to be an ImageView, and have a BroadCast Receiver redraw a single image every 20 minutes and then replace the image?

TL;DR Can I include a canvas object in a home screen widget which I redraw every 20ish minutes?

I'm having a hard time trying to figure out how to phrase the question to search for an answer, so any help in the right direction would be appreciated.

Upvotes: 0

Views: 2242

Answers (2)

Archimedes Trajano
Archimedes Trajano

Reputation: 41290

In your widget_layout.xml have an ImageView that will contain your drawing area

<ImageView
    android:id="@+id/widget_image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

In your AppWidgetProvider.onUpdate method, create a bitmap and make a Canvas from it that you can draw on. The larger the bitmap, the better the quality at the expense of performance.

Bitmap bitmap = Bitmap.createBitmap(400, 180, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);

When you are done painting on your canvas, update the widget using setImageViewBitmap

final RemoteViews remoteViews = new RemoteViews(
            context.getPackageName(), R.layout.widget_layout);
remoteViews.setImageViewBitmap(R.id.widget_image, bitmap);

Upvotes: 4

Pointer Null
Pointer Null

Reputation: 40380

Android's home screen widget using system of RemoteViews.

This means your app provides id of its layout, and some basic (limited) set of modifications to this layout, such as setting text, color, visibility, etc. All these modifications are written into "Parcel" and sent by system to other process which actually manages home screen items. This process will load the layout, unparcels modification data and aplies to layout.

So you see, you can't have any direct access to Canvas.

EDIT: one possibility to draw anything is to use RemoteViews.setBitmap, so you'd have any bitmap in the widget. But beware, Android guys say it is SLOW, as bitmap has to be stored to "parcel" which means converted to something like string, then convertet back to Bitmap on other part. If it's small image, it may work.

Upvotes: 2

Related Questions