我正在尝试从远程URL提取图像并将其放入ImageView。 ImageView本身位于应用程序小部件内,因此,根据我目前的理解,这意味着它被封装在RemoteViews中,并且实际上并未直接处理。
但是我永远无法获得应用小部件来显示图像。我正在使用AsyncTask扩展名从远程URL中以位图的形式获取图像,似乎图像正在获取OK(无论如何都返回非空位图),尽管到目前为止我仍无法显示该图像以进行确认。
我认为我必须使用错误的方法来实际更新应用程序小部件的ImageView。
这是所有相关代码:
布局/new_app_widget.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:contentDescription="@string/content" />
</RelativeLayout>
来自NewAppWidget.java的相关位:
public class NewAppWidget extends AppWidgetProvider {
...
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
String strURL = "http://example.com/YqLOSfr4.png";
new ImageFetchAsyncTask(strURL, R.id.imageView).execute();
// ^^^^^
// in the above, I pass the URL and the id of the imageview, fetch
// the bitmap, and in the onPostExecute() method I use
// setImageViewBitmap(viewId, bitmap) to load the bitmap into the imageview
//
// I don't have the code to hand, but I can provide it. For now, someone
// may be able to tell me somewhere else I'm doing something wrong
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.widgetapptest" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:debuggable="true"
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".NewAppWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/new_app_widget_info" />
</receiver>
</application>
</manifest>
最佳答案
经典初学者的错误...我正在尝试在异步任务之后立即执行某项操作,希望异步任务已完成。因此,我将依赖于异步任务结果的内容移到了异步任务的onPostExecute()方法中,瞧瞧……图像显示在我的应用程序小部件中!