RemoteView.setImageViewResource不显示任何内容

时间:2014-08-31 08:16:15

标签: android android-appwidget android-remoteview

我尝试在我的小工具中将图像设置为ImageView,但不是图片而是我的空白屏幕

这里的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">
<ImageView 
    android:id="@+id/stage"
  android:layout_width="match_parent"
 android:layout_height="match_parent"

    />
</RelativeLayout>

这里的代码:

public class MyWidget extends AppWidgetProvider {

      Bitmap bitmap;
      Bitmap bckgrnd;
      Bitmap over;

      @Override
      public void onEnabled(Context context) {
        super.onEnabled(context);

 RemoteViews widgetView = new RemoteViews(context.getPackageName(),
                R.layout.widget);
        bckgrnd=BitmapFactory.decodeResource(context.getResources(), R.drawable.backgrnd);
        over=BitmapFactory.decodeResource(context.getResources(), R.drawable.human);

        bitmap=bckgrnd.copy(Bitmap.Config.ARGB_8888, true);;
        Canvas c=new Canvas(bitmap);
        c.drawBitmap(over, 50, 50, new Paint());
        widgetView.setImageViewBitmap(R.id.stage, bitmap);



        Log.d("MyLog", "onEnabled");
      }

    ......
    }

所以,我有一个&#34; OnEnabled&#34;在我的LogCat中,这意味着此代码已执行良好,但ImageView仍为空。如果我在布局xml中设置任何图像 - 它会显示该图像,这意味着xml设置正确,但代码不会在ImageView中更改此图像。

我尝试在onUpdate()中执行此操作,但它也没有工作。 如何在ImageView中更改此图像?

2 个答案:

答案 0 :(得分:1)

我认为现在已经很晚了......但只是为了帮助那些仍在寻找的人。

对我而言,这有效..

// Change widget image, and update current app widget.
widgetView.setImageViewBitmap(R.id.stage, bitmap);
AppWidgetManager.getInstance(context).updateAppWidget(COMPONENT_NAME, widgetView);

而且,COMPONENT_NAME

COMPONENT_NAME = new ComponentName(context, MyWidget.class);

这将更新应用程序的每个小部件..如果您只想更新单击的小部件,请在widgetId中将COMPONENT_NAME代替updateAppWidget()。< / p>

答案 1 :(得分:1)

我遇到了类似的问题,除了我在onUpdate的后续调用中调用rv.setImageViewResource。

我的解决方案是您必须在xml文件中为ImageView设置初始图像,然后您可以在运行时更改ImageView的图片;如果你没有在xml中指定初始pic,那么setImageViewResource不起作用,ImageView什么都不显示。

更新

现在setImageViewResource运行良好无论ImageView在xml中是否有初始src,它都是有线的。