简体   繁体   English

Android如何将xml形状设置为小部件背景?

[英]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? 如何在Widget中将xml中定义的形状设置为图像的背景? 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. 这会导致android.graphics.drawable.GradientDrawable类强制转换异常。

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); 这会在awm.updateAppWidget(awID, views);上引发NullPointerException错误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. 这会导致第一行出现android.graphics.drawable.GradientDrawable类强制转换异常。

You can do it with the setInt method calling on the RemoteViews instance: 您可以通过调用RemoteViews实例的setInt方法来实现:

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). 为此,必须在小部件布局的View (可能是根视图)(在xml中)中将@id属性设置为"layout"

You can also define a background to that View from xml, like: 您还可以通过xml定义该视图的背景,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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