将数据从Widget配置发送到viewsFactory Android

时间:2017-05-25 13:21:18

标签: android listview widget

添加新窗口小部件时,会弹出配置活动弹出窗口,从数据库中扩展名称列表视图,当我从配置活动中选择名称时,它会将位置传递给Appwidget提供程序

 static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        final CharSequence recipeId = IngredientConfiguration.loadTitlePref(context, appWidgetId);

        String recipeIdInt = recipeId.toString();

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.ingredient_widget);

        Intent intent = new Intent(context, ListViewService.class);
        remoteViews.setRemoteAdapter(R.id.widget_listview, intent);

        remoteViews.setEmptyView(R.id.widget_listview, R.id.empty_view);

        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }

我创建了remoteviewservice工厂,它使用位置为0的光标从数据库中扩展listview。

我想从配置活动中获取信息并在remoteviewfactory中使用该值并使用唯一值对列表视图进行充气

1 个答案:

答案 0 :(得分:1)

只需将参数添加到适配器意图。看看一个简单的例子。

Intent intent = new Intent(context, ExampleRemoteService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
intent.putExtra("group", group);
intent.putExtra("week", week);
intent.putExtra("day", day);
remoteViews.setRemoteAdapter(R.id.example, intent);

在onGetViewFactory方法的ExampleRemoteService中,您可以获得此意图并转移到ExampleViewsFactory。

@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return (new ExampleViewsFactory(this.getApplicationContext(),
            intent));
}

在ExampleViewsFactory中获取所有intent的数据,而在OnCreate中只需加载列表取决于此参数。

private String group;
private int widgetId;
private int week;
private int day;
private List<ExampleModel> data = new ArrayList<>();

public ExampleViewsFactory(Context context, Intent adapter) {
    this.group = adapter.getStringExtra("group");
    this.day = adapter.getIntExtra("day", 0);
    this.week = adapter.getIntExtra("week", 0);
    this.widgetId = adapter.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID);
}

@Override
public void onCreate() {
    this.data = exampleRepository.getDataByWeekAndDay(group, week, day);
}

现在您只需要为所有项目制作远程视图。