简体   繁体   中英

How change button background twice at runtime in widget?

I have a widget, and contain some button. The buttons label string come from AsyncHTTPTask. I would change the button background is black before start internet connection and then receive data change button BG to green. The exampe doesn't work. I don't see black status, just finished green status.

        remoteViews.setInt(
                    context.getResources().getIdentifier("widget_button" + i, "id", context.getPackageName()),
                    "setBackgroundResource",
                    R.drawable.button_draw_black_gradient
                    );
        SystemClock.sleep(3000);
        try {
            jsonStr = new AsyncHTTPTask().execute(SURL).get();
        } catch (InterruptedException e) {
        ....
        remoteViews.setInt(
                    context.getResources().getIdentifier("widget_button" + i, "id", context.getPackageName()),
                    "setBackgroundResource",
                    R.drawable.button_draw_green_gradient
                    );

Try to request the view's layout and manually refresh the view by calling invalidate :

    remoteViews.requestLayout();
    remoteViews.setInt(
                context.getResources().getIdentifier("widget_button" + i, "id", context.getPackageName()),
                "setBackgroundResource",
                R.drawable.button_draw_black_gradient
                );
    remoteViews.invalidate();

And i think there is something wrong with your code. You should change the button to green when AsyncTask has finished its task.

So move this code to the onPost :

    remoteViews.requestLayout();
    remoteViews.setInt(
                context.getResources().getIdentifier("widget_button" + i, "id", context.getPackageName()),
                "setBackgroundResource",
                R.drawable.button_draw_green_gradient
                );
    remoteViews.invalidate();

I solved my problem now. This part make force upadte:

ComponentName thisWidget = new ComponentName(context,FooBar.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM