从Xamarin Android中的应用程序活动更新Widget内的文本视图?

gr8qqesn  于 2022-12-07  发布在  Android
关注(0)|答案(2)|浏览(141)

我有一个包含TextView的小部件。我尝试从MainaActivity更新小部件数据,因为从主Activity添加了更多数据,我希望小部件刷新

class TodoWidget : AppWidgetProvider
{
..............

    private void SetTextViewText(RemoteViews widgetView)
    {
       // widgetView.SetTextViewText(Resource.Id.widgetMedium, new TodoDBR().GetAllRecordsForWidget());
        widgetView.SetTextViewText(Resource.Id.widgetSmall, new TodoDBR().GetAllRecordsForWidget());
    }

在Main Activity中,添加数据后,我尝试调用方法来更新微件,但它不起作用

AppWidgetManager appWidgetManager = AppWidgetManager.GetInstance(this.Context);
        var manager = AppWidgetManager.GetInstance(this.Context);
        var componentName = new ComponentName(Context.PackageName, Java.Lang.Class.FromType(typeof(TodoWidget)).Name);

        int[] appWidgetIds = appWidgetManager.GetAppWidgetIds(componentName);
            appWidgetManager.NotifyAppWidgetViewDataChanged(appWidgetIds, Resource.Layout.TodoWidget);

它没有更新我的小工具

pexxcrt2

pexxcrt21#

如果我自己找到了答案,以防其他人也有同样的问题,这里是解决方案

RemoteViews remoteViews = new RemoteViews(Context.PackageName, Resource.Layout.TodoWidget);
        ComponentName thisWidget = new ComponentName(this.Context, Java.Lang.Class.FromType(typeof(TodoWidget)).Name);
        remoteViews.SetTextViewText(Resource.Id.widgetSmall, new TodoDBR().GetAllRecordsForWidget());
        AppWidgetManager.GetInstance(this.Context).UpdateAppWidget(thisWidget, remoteViews);
xj3cbfub

xj3cbfub2#

不能投票,但谢谢你-经过4年。终于它的工作为我。对于某人也,调用更新小部件从主或服务:

    • 致电更新:任何地点、服务计时器或主要活动等:**
public void updateWidgets()
{
    Intent brIntent = new Intent(AppWidgetManager.ActionAppwidgetUpdate);
    SendBroadcast(brIntent);
}
    • 接收更新:小部件文件. cs:**
public override void OnReceive(Context context, Intent intent) {
    RemoteViews remoteViews = new RemoteViews(Context.PackageName, Resource.Layout.**TodoWidget**);
    ComponentName thisWidget = new ComponentName(context, Java.Lang.Class.FromType(typeof(**TodoWidget**)));
    remoteViews.SetTextViewText(Resource.Id.widgetSmall, "Hello world");
    AppWidgetManager.GetInstance(this.Context).UpdateAppWidget(thisWidget, remoteViews);
}

接下来是. SetAction()

相关问题