18
votes

I am creating a appwidget that consists of a single custom view called Foo.

xml/widget.xml:

<appwidget-provider
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:minWidth="294dp"
 android:minHeight="72dp"
 android:updatePeriodMillis="0"
 android:initialLayout="@layout/widget_layout">
</appwidget-provider>

layout/widget_layout

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <package.name.Foo
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 />
</LinearLayout>

Foo:

  public class Foo extends View 
  {..}

I tested the Foo view in a normal android app, and it works perfectly. However, when I try to run the widget I get "error while loading widget". When I remove the Foo view from the widget, everything is fine. So it has something to do with the Foo view.

Unfortunately I can't get any more specific errors in DDMS, cause I don't know of a way to debug widgets.

I would like to know if it is indeed possible to use your own custom views in a app-widget? Am I doing something wrong here?

4
What's in your Foo view? You can only have certain views in a widget. I'm not even sure you can instantiate a widget with a view created with code.Falmarri
I had created a totally custom drawn dynamically updated visual thingy. Nice as a widget, but I guess I'll try now to render it to a bitmap in the provider and push it to a imageview that is supported.Peterdk
Yes. That's exactly same way I did for my widget animation.xandy

4 Answers

48
votes

I pretty much left my custom view intact, and implemented an ImageView for my widget, then rendered the view using the getDrawingCache()

MyView myView = new MyView(context);
myView.measure(150,150);
myView.layout(0,0,150,150);
myView.setDrawingCacheEnabled(true);
Bitmap bitmap=myView.getDrawingCache();
remoteViews.setImageViewBitmap(R.id.dial, bitmap);
14
votes

Another way to do this without using getDrawingCache() :

MyView myView = new MyView(this);
myView.measure(500, 500);
myView.layout(0, 0, 500, 500);
Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
myView.draw(new Canvas(bitmap));
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);

I used cache not to redraw all the view so I couldn't use the code above. And I find it more elegant. I hope it could be useful to someone.

8
votes

see the documentation.

AnalogClock, Button, Chronometer, ImageButton, ImageView, ProgressBar and TextView are the supported views. For layouts you have to use FrameLayout, LinearLayout or RelativeLayout.

7
votes

You cannot have ANY custom view used in widget. In fact, even those android-predfined views are not all supported.

For detailed list of supported widgets/layouts, please read the documentation. Anything other than those documented cannot be placed in widgets.