【发布时间】:2015-06-18 17:29:57
【问题描述】:
我是 android 开发的新手。我正在尝试使用 Web 服务在我的小部件中加载列表视图。它加载完美,但我想根据我的要求动态更新我的列表视图。
这里附上我的代码:
package com.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;
public class WidgetProvider extends AppWidgetProvider {
public static final String DATA_FETCHED = "com.widget.DATA_FETCHED";
public static String UPDATE_LIST = "UPDATE_LIST";
AppWidgetManager appWidgetManager;
ComponentName currentWidget;
public static Integer randomNumber;
SharedPreferences sharedprefer;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
Intent serviceIntent = new Intent(context, RemoteFetchService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetIds[i]);
context.startService(serviceIntent);
// appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i],
// R.id.listViewWidget);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listViewWidget);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(DATA_FETCHED)) {
int appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
RemoteViews remoteViews = updateWidgetListView(context, appWidgetId);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId,
R.id.listViewWidget);
}
}
private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
Intent svcIntent = new Intent(context, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setRemoteAdapter(appWidgetId, R.id.listViewWidget,
svcIntent);
remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);
updateWidget(context, remoteViews);
return remoteViews;
}
public static void updateWidget(Context context, RemoteViews remoteViews) {
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
int appWidgetIds[] = appWidgetManager
.getAppWidgetIds(new ComponentName(context,
WidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds,
R.id.listViewWidget);
}
}
【问题讨论】:
标签: android android-listview arraylist android-widget