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

标签 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();
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/

相关文章:

css - 修复 WordPress 页面中的表格垂直居中

c++ - Qt Widget布局背景

ios - 今日扩展 iOS 10 Swift,显示较少

android - 弹出窗口的事件方法未触发

android - android应用程序中的闹钟声音

android - 按下按钮拍摄并保存照片

flutter - 如何在布局中随机放置小部件

Android – 是否可以使用非字符串参数制作 Http-Post?

Java/解析错误。试图从 android sdk 发送到 Parse

Android 小部件设置 android :updatePeriodMillis programmatically