2

我有一个小部件,用于在每次收到更新广播时更改其图标。但是,小部件永远无法正确显示其图标,显示文本“问题加载小部件”。Logcat 消息是:

WARN/AppWidgetHostView(612): updateAppWidget couldn't find any view, using error view
WARN/AppWidgetHostView(612): android.widget.RemoteViews$ActionException: can't find view: 0x7f060003

我的 onUpdate 的代码是:

public class ImageWidgetProvider extends AppWidgetProvider{
private  static final String TAG = "Steve";

public static final int[] IMAGES = { R.drawable.ic_launcher_alarmclock,
    /*and many more*/};

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){

    for (int appWidgetId : appWidgetIds) {
        Log.d(TAG, "onUpdate:");
        int imageNum = (new java.util.Random().nextInt(IMAGES.length));
        Log.d(TAG, Integer.toString(IMAGES[imageNum]));
        RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
        remoteView.setImageViewResource(R.id.image_in_widget, IMAGES[imageNum]);
        appWidgetManager.updateAppWidget(appWidgetId, remoteView);
    }

}
}

现在,当我将鼠标悬停在“R.id.image_in_widget”上时,它会显示其值等于 0x7f060003 - 根据 Logcat 无法找到的视图。使用第二个 Log 语句,我验证了 IMAGES[imageNum] 确实引用了 IMAGES 数组中的随机图像。(如果它很重要,它会以十进制值而不是十六进制值出现。)任何想法我做错了什么?非常感谢!

--

编辑:这是小部件的布局文件,其中声明了 image_in_widget ImageView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView android:name="@+id/image_in_widget"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>
4

3 回答 3

2

这可能发生的另一个原因(对于那些在这个问题上搜索网络的人,比原始海报更多):

如果您有横向与纵向的单独布局,则这两个布局都必须包含您在更新期间引用的任何视图。如果您引用仅在一种模式下存在的视图,例如纵向,那么在横向中,您将在小部件框中收到“问题加载小部件”消息。

简单的解决方案是在您不希望这些视图出现的模式下将可见性设置为“GONE”。

于 2010-07-11T05:05:35.330 回答
1

Android 1.5 存在不为小部件调用 OnDelete 的问题。

将此代码放在您的 AppWidgetProvider 中,它应该可以解决问题

public void onReceive(Context context, Intent intent) {
    // v1.5 fix that doesn't call onDelete Action
    final String action = intent.getAction();
    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
        final int appWidgetId = intent.getExtras().getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            this.onDeleted(context, new int[] { appWidgetId });
        }
    } else {
        super.onReceive(context, intent);
    }
}
于 2010-02-10T12:59:17.323 回答
0

也许它不适用于您的示例,但我也遇到了与应用程序小部件类似的问题。在 android 1.5 中,主屏幕小部件存在一个烦人的问题。在特定情况下,应用程序小部件在内存中仍然处于活动状态,但不再可见。
您正在通过 appWidgetIds 进行枚举,请检查此数组是否包含您期望的 id 数量。只需放置另一个 Log.d() 来记录 ID。也许你也有一些“幽灵”小部件。
你用的是什么安卓版本?

于 2009-12-29T22:42:16.597 回答