如何识别点击的小部件?

时间:2017-03-16 09:35:35

标签: android widget

我在主屏幕上创建了三个小部件,我想分别更改每个小部件的视图。因此,当我单击小部件时,它总是检测到我单击最后创建的小部件(请参阅下面显示的onReceive方法中的Toast)。如何分别检测来自不同小部件的点击并识别活动小部件?

这是我的代码:

public class SimpleWidgetProvider extends AppWidgetProvider {

    private final String TAG="SimpleWidgetTAG" ;
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int count = appWidgetIds.length;

        Log.i(TAG,"  onUpdate ") ;

        for (int i = 0; i < count; i++) {
            int widgetId = appWidgetIds[i];
            String number = String.format("Item %d =  %03d ", i,(new Random().nextInt(900) + 100));

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                    R.layout.simple_widget);
            remoteViews.setTextViewText(R.id.textView, number);

            Intent intent = new Intent(context, SimpleWidgetProvider.class);
            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);

            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        int widgetID = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

        if(intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
            Toast.makeText(context, "Updated " + widgetID, Toast.LENGTH_LONG).show();
        }

        Log.i(TAG,"  onReceive "+intent+"  , \n widgetId = "+widgetID) ;

    }

}

0 个答案:

没有答案