简体   繁体   中英

Android How to set an xml shape as widget background?

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.

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM