【问题标题】:Android How to set an xml shape as widget background?Android 如何将 xml 形状设置为小部件背景?
【发布时间】:2012-05-24 05:23:46
【问题描述】:

如何将 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 类转换异常。

【问题讨论】:

    标签: android widget


    【解决方案1】:

    您可以通过调用RemoteViews 实例的setInt 方法来做到这一点:

    views.setInt(R.id.layout, "setBackgroundResource", R.drawable.widgetshape);
    

    为此,您必须在小部件布局的View(可能是根视图)上将@id 属性设置为"layout"(以xml 格式)。 p>

    您还可以从 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 找不到任何视图,使用错误视图。我不明白为什么会这样说
    • 请查看此线程:stackoverflow.com/a/7299587/506879 并创建必要的构造函数来消除此问题。如果您更改了任何资源,也要清理并重新编译您的项目:ant 经常会错过更改。
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多