【问题标题】:setTextViewText not updating widgetsetTextViewText 不更新小部件
【发布时间】:2011-05-24 22:11:14
【问题描述】:

下面显示的是我的课程的简化版本。我在未更新小部件 TextView 的 onReceive 方法中遇到问题。它在 setTextViewText 之前的行上输出的 logcat 中显示正确的信息。我不知道怎么了,一直在拔头发(而且我已经秃顶了)。

public class SnowWidget extends AppWidgetProvider {

public static List<Article> mymtns = new ArrayList<Article>();
public static RemoteViews remoteViews;
public static ComponentName thisWidget;

public static String amount = "";
public static String mtn_name = "";
public static String desc = "";
public static String condition = "";
public static String[] type;

public static int index = 0;

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

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

    thisWidget = new ComponentName(context, SnowWidget.class);

    // This one works fine
    remoteViews.setTextViewText(R.id.snowwidget,  mtn_name+ "\n"+ amount+"\"\n"+ condition);

    /* Make the buttons work */

Intent next = new Intent(context, SnowWidget.class);
next.setAction(ACTION_WIDGET_RECEIVER);

PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, next, 0);
remoteViews.setOnClickPendingIntent(R.id.nextMtn, nextPendingIntent);

/* END - Make the buttons work */

    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}

@Override
public void onReceive(Context context, Intent intent) {

    // check, if our Action was called
    if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
        if(mymtns.size() > 0)
        {

            // This show up correctly in logcat
            Log.d("onReceive", "New Info => "+ mtn_name+ "\n"+ amount+"\"\n"+ condition);
            // This never updates my widget
            remoteViews.setTextViewText(R.id.snowwidget,  mtn_name+ "\n"+ amount+"\"\n"+ condition);

        }
    }

    super.onReceive(context, intent);
}

}

【问题讨论】:

    标签: java android android-widget


    【解决方案1】:

    找到了答案。调用remoteViews.setTextViewText 后,您需要调用updateAppWidget 来更新小部件。我添加的代码如下所示。

    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(thisWidget, remoteViews);
    

    【讨论】:

    • 非常感谢!很难描述这个问题给我带来了多大的头痛。
    • 我有这段代码,但它仍然无法正常工作.. 虽然它以前是。我不知道发生了什么。
    • 你在哪里添加那几行代码?我似乎无法让我的小部件工作。
    • 我为未更新 widgetId 的配置活动传递了错误的标志:PendingIntent.getActivity(context, 0, intent, 0) 而不是:PendingIntent.getActivity(context, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT)
    • 感谢 Ivan,我在使用 FLAG_ONE_SHOT 时出现了奇怪的行为,当我将标志设置为 0 时,它不再刷新。
    猜你喜欢
    • 2014-05-14
    • 2012-01-06
    • 1970-01-01
    • 2021-07-10
    • 2011-10-04
    • 2016-11-18
    • 2013-05-01
    • 2021-08-06
    • 2018-11-01
    相关资源
    最近更新 更多