Note that there are some explanatory texts on larger screens.

plurals
  1. POOnly update the current Android widget ID in update method
    text
    copied!<p>I'm making a widget in android which produces a random number when clicked. When the widget is alone on the home screen it works perfectly, however when you add multiple of them they start to generate random numbers at the same time. Whats happening is when an individual widget is clicked it updates all of them; resulting in many random numbers. What i want is each widget to be isolated from the others; basically when a widget is clicked it only updates itself and non of the others around it. I think this is achievable by getting the ID of the current widget and update that one only, as apposed to the update method updating all the widgets; how do i do this?</p> <p>My code</p> <pre><code>@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Get all ids ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { // Create some random data int number = (new Random().nextInt(100)); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); Log.w("WidgetExample", String.valueOf(number)); // Set the text remoteViews.setTextViewText(R.id.update, String.valueOf(number)); // Register an onClickListener Intent intent = new Intent(context, MyWidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent); appWidgetManager.updateAppWidget(widgetId, remoteViews); } } </code></pre> <p><em>Summary:</em> </p> <p>This code is the update method and is called when a widget is clicked. I want this method to only update the widget ID that called it, not for this method to update all the widgets ID's on the home screen.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload