如何将 xml 中定义的形状设置为小部件中图像的背景? 这是我的尝试:
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);
这会导致 android.graphics.drawable.GradientDrawable 类转换异常。
Bitmap icon = BitmapFactory.decodeResource(WidgetConfig.this.getResources(), R.drawable.widgetshape);
views.setImageViewBitmap(R.id.ImageView01, icon);
这会在 awm.updateAppWidget(awID, views);
行上引发 NullPointerException 错误。
Bitmap bp = ((BitmapDrawable)this.getResources().getDrawable(R.drawable.widgetshape)).getBitmap(); //Class Cast Exception
views.setImageViewBitmap(R.id.ImageView01, bp);
这会导致第一行出现 android.graphics.drawable.GradientDrawable 类转换异常。
最佳答案
您可以通过调用 RemoteViews
实例的 setInt
方法来实现:
views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);
为此,您必须在 View
上将 @id
属性设置为 "layout"
>(可能是 Root View )您的小部件布局(在 xml 中)。
您还可以从 xml 为该 View 定义背景,例如:
<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">
关于Android 如何将 xml 形状设置为小部件背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10622082/