1

How can I set a shape defined in xml as background of an image in a widget? Here are my attempts:

RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget_layout);

Drawable dr = getResources().getDrawable(R.drawable.widgetshape);  //class cast exception
Bitmap bp = ((BitmapDrawable)dr).getBitmap();
views.setImageViewBitmap(R.id.ImageView01, bp);

This results in an android.graphics.drawable.GradientDrawable class cast exception.

Bitmap icon = BitmapFactory.decodeResource(WidgetConfig.this.getResources(),  R.drawable.widgetshape);
views.setImageViewBitmap(R.id.ImageView01, icon);

This throws a NullPointerException error on the awm.updateAppWidget(awID, views); line.

Bitmap bp = ((BitmapDrawable)this.getResources().getDrawable(R.drawable.widgetshape)).getBitmap(); //Class Cast Exception
views.setImageViewBitmap(R.id.ImageView01, bp);

This results in an android.graphics.drawable.GradientDrawable class cast exception on the first line.

erdomester
  • 11,789
  • 32
  • 132
  • 234

1 Answers1

1

You can do it with the setInt method calling on the RemoteViews instance:

views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);

For this to work, you must have an @id attribute set to "layout" on the View (probably the root view) of your widget layout (in xml).

You can also define a background to that View from xml, like:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout" android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/widgetshape">
rekaszeru
  • 19,130
  • 7
  • 59
  • 73
  • What problem do you have? do you happen to have the logcat output to share? Both of the above implementations work just fine for me. – rekaszeru May 16 '12 at 16:16
  • Logcat says: updateAppWidget couldn't find any view, using error view. I don't understand why does it say that – erdomester May 16 '12 at 16:19
  • please see this thread: http://stackoverflow.com/a/7299587/506879 and create the necessary constructor(s) to eliminate this problem. Also clean and recompile your project if you have changed any resources: ant often misses the changes. – rekaszeru May 16 '12 at 16:46