Android如何将xml形状设置为小部件背景?
如何将xml中定义的形状设置为小部件中图像的背景? 以下是我的尝试:Android如何将xml形状设置为小部件背景?,android,widget,Android,Widget,如何将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(
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,视图)上引发NullPointerException错误代码>行
Bitmap bp = ((BitmapDrawable)this.getResources().getDrawable(R.drawable.widgetshape)).getBitmap(); //Class Cast Exception
views.setImageViewBitmap(R.id.ImageView01, bp);
这将导致第一行出现android.graphics.drawable.GradientDrawable类强制转换异常。您可以通过调用RemoteView
实例的setInt
方法执行此操作:
views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);
要使其工作,您必须在小部件布局(xml格式)的视图(可能是根视图)上将@id
属性设置为“布局”
您还可以从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">
您可以通过调用remoteview
实例的setInt
方法来实现:
views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);
要使其工作,您必须在小部件布局(xml格式)的视图(可能是根视图)上将@id
属性设置为“布局”
您还可以从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">
您有什么问题?您是否有要共享的logcat输出?以上两种实现对我来说都很好。Logcat说:updateAppWidget使用错误视图找不到任何视图。我不明白为什么它说请看这个线程:并创建必要的构造函数来消除这个问题。如果您更改了任何资源,也要清理并重新编译您的项目:ant经常忽略这些更改。您有什么问题?您是否有要共享的logcat输出?以上两种实现对我来说都很好。Logcat说:updateAppWidget使用错误视图找不到任何视图。我不明白为什么它说请看这个线程:并创建必要的构造函数来消除这个问题。如果您更改了任何资源,也要清理并重新编译您的项目:ant经常忽略这些更改。