Utilizzo dei widget raccolta

I widget della raccolta sono specializzati nella visualizzazione di molti elementi dello stesso tipo, ad esempio: come raccolte di immagini da un'app Galleria, articoli di un'app di notizie o i messaggi da un'app di comunicazione. I widget della raccolta si concentrano in genere su due casi: l'esplorazione della raccolta e l'apertura di un elemento della raccolta la visualizzazione dei dettagli. I widget della raccolta possono scorrere in verticale.

Questi widget utilizzano RemoteViewsService per visualizzare raccolte supportate da dati remoti, ad esempio di contenuti o il provider. Il widget presenta i dati utilizzando uno dei seguenti tipi di viste, noti come raccolta visualizzazioni:

ListView
Una visualizzazione che mostra gli elementi in una a scorrimento verticale.
GridView
Una visualizzazione che mostra gli elementi in una griglia di scorrimento bidimensionale.
StackView
Una scheda in pila simile a un rolodex, in cui l'utente può ruotare la parte anteriore verso l'alto o verso il basso per vedere rispettivamente la scheda precedente o successiva.
AdapterViewFlipper
Un semplice basato su adattatore ViewAnimator che si anima tra due o più visualizzazioni. Viene mostrato un solo bambino alla volta.

Poiché queste visualizzazioni delle raccolte mostrano raccolte supportate da dati remoti, utilizza una Adapter per vincolare l'utente ai loro dati. Un elemento Adapter associa singoli elementi a un set di dati ai singoli oggetti View.

Poiché queste visualizzazioni raccolta sono supportate da adattatori, il framework Android devono includere un'ulteriore architettura per supportarne l'uso nei widget. Nel contesto di un widget, Adapter viene sostituito da RemoteViewsFactory, che è un sottile wrapper intorno all'interfaccia di Adapter. Quando viene richiesto elemento specifico della raccolta, l'RemoteViewsFactory crea e restituisce l'elemento per la raccolta come RemoteViews. Per includere un visualizzazione raccolta nel widget, implementare RemoteViewsService e RemoteViewsFactory.

RemoteViewsService è un servizio che consente a una richiesta di adattatore remoto RemoteViews oggetti. RemoteViewsFactory è un'interfaccia per un adattatore tra una visualizzazione raccolta, come ListView, GridView e StackView e i dati sottostanti per la vista in questione. Da StackWidget esempio, Ecco un esempio del codice boilerplate per implementare questo servizio e dell'interfaccia:

Kotlin

class StackWidgetService : RemoteViewsService() {

    override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
        return StackRemoteViewsFactory(this.applicationContext, intent)
    }
}

class StackRemoteViewsFactory(
        private val context: Context,
        intent: Intent
) : RemoteViewsService.RemoteViewsFactory {

// See the RemoteViewsFactory API reference for the full list of methods to
// implement.

}

Java

public class StackWidgetService extends RemoteViewsService {
    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
    }
}

class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {

// See the RemoteViewsFactory API reference for the full list of methods to
// implement.

}

Applicazione di esempio

Anche gli estratti del codice di questa sezione sono tratti dal StackWidget esempio:

Figura 1. Un StackWidget.

Questo esempio è costituito da uno stack di dieci viste che mostrano il valore zero alle nove. Il widget di esempio ha i seguenti comportamenti principali:

  • L'utente può scorrere verticalmente la visualizzazione dall'alto nel widget per mostrare la o la visualizzazione precedente. Questo è un comportamento StackView integrato.

  • Senza alcuna interazione dell'utente, il widget avanza automaticamente nella visualizzazioni in sequenza, come in una presentazione. Ciò è dovuto all'impostazione android:autoAdvanceViewId="@id/stack_view" in res/xml/stackwidgetinfo.xml file. Questa impostazione si applica all'ID vista, che in questo caso è l'ID della visualizzazione in pila.

  • Se l'utente tocca la vista dall'alto, il widget mostra la Toast il messaggio "Visualizzazione toccata N" dove n è l'indice (posizione) della visualizzazione touch. Per ulteriori discussioni su come per implementare comportamenti, consulta la sezione Aggiungere un comportamento a singole elementi.

Implementare widget con le raccolte

Per implementare un widget con raccolte, segui la procedura per implementare qualsiasi widget, seguiti da altri passaggi: modificare il file manifest, aggiungere una visualizzazione raccolta al layout del widget e modificare AppWidgetProvider.

Manifest per i widget con raccolte

Oltre ai requisiti elencati nella sezione Dichiarare un widget nel , devi rendere possibile i widget con raccolte da associare a RemoteViewsService. Per farlo, devi dichiarare nel file manifest con l'autorizzazione BIND_REMOTEVIEWS In questo modo altre applicazioni non possono accedere liberamente ai dati del widget.

Ad esempio, quando crei un widget che utilizza RemoteViewsService per compilare una visualizzazione raccolta, la voce del file manifest potrebbe avere il seguente aspetto:

<service android:name="MyWidgetService"
    android:permission="android.permission.BIND_REMOTEVIEWS" />

In questo esempio, android:name="MyWidgetService" si riferisce alla tua sottoclasse RemoteViewsService.

Layout per widget con raccolte

Il requisito principale per il file XML di layout del widget è che includa uno dei visualizzazioni raccolta: ListView, GridView, StackView o AdapterViewFlipper. Ecco il file widget_layout.xml per StackWidget esempio:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <StackView
        android:id="@+id/stack_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:loopViews="true" />
    <TextView
        android:id="@+id/empty_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/widget_item_background"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:text="@string/empty_view_text"
        android:textSize="20sp" />
</FrameLayout>

Tieni presente che le viste vuote devono essere di pari livello della vista raccolta per la quale visualizzazione vuota rappresenta uno stato vuoto.

Oltre al file di layout per l'intero widget, crea un altro layout file che definisce il layout di ogni elemento della raccolta, ad esempio un layout per ogni libro in una raccolta. Il campione StackWidget ha un solo file di layout di elemento, widget_item.xml, poiché tutti gli elementi utilizzano lo stesso layout.

Classe AppWidgetProvider per widget con raccolte

Come con i normali widget, la maggior parte del codice nel tuo Sottoclasse AppWidgetProvider di solito entra onUpdate(). La principale differenza nella tua implementazione per onUpdate() quando crei con le raccolte è necessario chiamare setRemoteAdapter() Questo indica alla vista raccolta dove recuperare i dati. RemoteViewsService può quindi restituire la tua implementazione di RemoteViewsFactory e il widget sarà in grado di distribuire i dati appropriati. Quando questo metodo, trasmetti un intent che punti all'implementazione RemoteViewsService e l'ID widget che specifica il widget da aggiornare.

Ad esempio, ecco come l'esempio StackWidget implementa l'elemento onUpdate() per impostare RemoteViewsService come adattatore remoto per raccolta widget:

Kotlin

override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
) {
    // Update each of the widgets with the remote adapter.
    appWidgetIds.forEach { appWidgetId ->

        // Set up the intent that starts the StackViewService, which
        // provides the views for this collection.
        val intent = Intent(context, StackWidgetService::class.java).apply {
            // Add the widget ID to the intent extras.
            putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
            data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
        }
        // Instantiate the RemoteViews object for the widget layout.
        val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
            // Set up the RemoteViews object to use a RemoteViews adapter.
            // This adapter connects to a RemoteViewsService through the
            // specified intent.
            // This is how you populate the data.
            setRemoteAdapter(R.id.stack_view, intent)

            // The empty view is displayed when the collection has no items.
            // It must be in the same layout used to instantiate the
            // RemoteViews object.
            setEmptyView(R.id.stack_view, R.id.empty_view)
        }

        // Do additional processing specific to this widget.

        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds)
}

Java

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // Update each of the widgets with the remote adapter.
    for (int i = 0; i < appWidgetIds.length; ++i) {

        // Set up the intent that starts the StackViewService, which
        // provides the views for this collection.
        Intent intent = new Intent(context, StackWidgetService.class);
        // Add the widget ID to the intent extras.
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
        // Instantiate the RemoteViews object for the widget layout.
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        // Set up the RemoteViews object to use a RemoteViews adapter.
        // This adapter connects to a RemoteViewsService through the specified
        // intent.
        // This is how you populate the data.
        views.setRemoteAdapter(R.id.stack_view, intent);

        // The empty view is displayed when the collection has no items.
        // It must be in the same layout used to instantiate the RemoteViews
        // object.
        views.setEmptyView(R.id.stack_view, R.id.empty_view);

        // Do additional processing specific to this widget.

        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

Mantieni i dati

Come descritto in questa pagina, la sottoclasse RemoteViewsService fornisce RemoteViewsFactory utilizzato per completare la visualizzazione della raccolta remota.

In particolare, segui questi passaggi:

  1. Sottoclasse RemoteViewsService. RemoteViewsService è il servizio tramite che un adattatore remoto può richiedere RemoteViews.

  2. Nella sottoclasse RemoteViewsService, includi una classe che implementa la classe RemoteViewsFactory. RemoteViewsFactory è un'interfaccia per un adattatore tra una visualizzazione raccolta remota, come ListView, GridView e StackView e i dati sottostanti per la vista in questione. Il tuo responsabile della creazione di un oggetto RemoteViews per ogni nel set di dati. Questa interfaccia è un wrapper sottile attorno a Adapter.

Non puoi fare affidamento su una singola istanza del tuo servizio, o su qualsiasi dato che contiene, per rimangono invariate. Non archiviare dati in RemoteViewsService a meno che non siano statici. Se Se vuoi che i dati del widget rimangano persistenti, l'approccio migliore è utilizzare una ContentProvider i cui dati persiste anche dopo il ciclo di vita del processo. Ad esempio, un widget di un negozio di alimentari archiviare lo stato di ogni articolo della lista della spesa in una posizione permanente, come un database SQL.

I contenuti principali dell'implementazione RemoteViewsService sono RemoteViewsFactory, descritto nella sezione seguente.

Interfaccia RemoteViewsFA

La classe personalizzata che implementa l'interfaccia RemoteViewsFactory fornisce al widget con i dati degli elementi della raccolta. Per fare ciò, Combina il file di layout XML degli elementi del widget con un'origine di dati. Questa fonte di I dati possono essere qualsiasi cosa, da un database a un semplice array. In StackWidget l'origine dati è un array di WidgetItems. RemoteViewsFactory funziona da adattatore per incollare i dati nella vista raccolta remota.

I due metodi più importanti da implementare RemoteViewsFactory sottoclasse onCreate() e getViewAt().

Il sistema chiama il numero onCreate() quando viene creata la fabbrica per la prima volta. Qui puoi configurare eventuali connessioni o cursori all'origine dati. Per Esempio, l'esempio StackWidget utilizza onCreate() per inizializzare un array di WidgetItem oggetti. Quando il widget è attivo, il sistema accede a questi utilizzando la posizione dell'indice nell'array e visualizza il testo che contengono.

Ecco un estratto dell'anteprima RemoteViewsFactory del StackWidget implementazione che mostra parti del metodo onCreate():

Kotlin

private const val REMOTE_VIEW_COUNT: Int = 10

class StackRemoteViewsFactory(
        private val context: Context
) : RemoteViewsService.RemoteViewsFactory {

    private lateinit var widgetItems: List<WidgetItem>

    override fun onCreate() {
        // In onCreate(), set up any connections or cursors to your data
        // source. Heavy lifting, such as downloading or creating content,
        // must be deferred to onDataSetChanged() or getViewAt(). Taking
        // more than 20 seconds on this call results in an ANR.
        widgetItems = List(REMOTE_VIEW_COUNT) { index -> WidgetItem("$index!") }
        ...
    }
    ...
}

Java

class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
    private static final int REMOTE_VIEW_COUNT = 10;
    private List<WidgetItem> widgetItems = new ArrayList<WidgetItem>();

    public void onCreate() {
        // In onCreate(), setup any connections or cursors to your data
        // source. Heavy lifting, such as downloading or creating content,
        // must be deferred to onDataSetChanged() or getViewAt(). Taking
        // more than 20 seconds on this call results in an ANR.
        for (int i = 0; i < REMOTE_VIEW_COUNT; i++) {
            widgetItems.add(new WidgetItem(i + "!"));
        }
        ...
    }
...

Il metodo RemoteViewsFactory getViewAt() restituisce un oggetto RemoteViews corrispondenti ai dati nel valore position specificato nel set di dati. Ecco un estratto dell'implementazione di RemoteViewsFactory dell'esempio StackWidget:

Kotlin

override fun getViewAt(position: Int): RemoteViews {
    // Construct a remote views item based on the widget item XML file
    // and set the text based on the position.
    return RemoteViews(context.packageName, R.layout.widget_item).apply {
        setTextViewText(R.id.widget_item, widgetItems[position].text)
    }
}

Java

public RemoteViews getViewAt(int position) {
    // Construct a remote views item based on the widget item XML file
    // and set the text based on the position.
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_item);
    views.setTextViewText(R.id.widget_item, widgetItems.get(position).text);
    return views;
}

Aggiungi un comportamento a singoli elementi

Le sezioni precedenti mostrano come associare i tuoi dati alla raccolta di widget. Ma E se volessi aggiungere un comportamento dinamico ai singoli elementi nel tuo visualizzazione raccolta?

Come descritto in Gestire gli eventi con onUpdate() , di solito usi setOnClickPendingIntent() per impostare il comportamento del clic di un oggetto, ad esempio causerà l'avvio di un pulsante Activity. Ma questo approccio non è consentito per le visualizzazioni secondarie in un singolo elemento della raccolta. Ad esempio, puoi utilizzare setOnClickPendingIntent() per configurare un pulsante globale nel widget Gmail che avvia l'app, ad esempio, ma non nella singole voci dell'elenco.

Per aggiungere il comportamento del clic a singoli elementi di una raccolta, utilizza setOnClickFillInIntent() Ciò comporta la configurazione di un modello di intent in attesa visualizzazione della raccolta e poi impostare un intento di compilazione per ciascun elemento nella raccolta tramite RemoteViewsFactory.

In questa sezione viene utilizzato l'esempio StackWidget per descrivere come aggiungere un comportamento a singoli elementi. Nell'esempio di StackWidget, se l'utente tocca la vista dall'alto, nel widget viene visualizzato il messaggio Toast "Vista toccata n", dove n è la indice (posizione) della vista toccata. Ecco come funziona:

  • StackWidgetProvider: una AppWidgetProvider crea un intent in attesa con un'azione personalizzata denominata TOAST_ACTION.

  • Quando l'utente tocca una visualizzazione, l'intent si attiva e trasmette TOAST_ACTION.

  • Questa trasmissione è intercettata dal comando della classe StackWidgetProvider onReceive() e il widget visualizza il messaggio Toast per la vista toccata. I dati relativi agli elementi della raccolta sono forniti dalla RemoteViewsFactory tramite RemoteViewsService.

di Gemini Advanced.

Configura il modello di intent in attesa

Il StackWidgetProvider (un sottoclasse AppWidgetProvider) un intent in attesa. I singoli elementi di una raccolta non possono configurare il relativo intent in attesa. Invece, la raccolta nel suo insieme configura un intent in attesa e i singoli elementi impostano un intento di compilazione per creare modelli il comportamento di ogni elemento.

Questa classe riceve anche la trasmissione inviata quando l'utente tocca una vista. Elabora questo evento nel suo metodo onReceive(). Se l'intent L'azione è TOAST_ACTION, il widget visualizza un messaggio Toast per l'attuale vista.

Kotlin

const val TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION"
const val EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM"

class StackWidgetProvider : AppWidgetProvider() {

    ...

    // Called when the BroadcastReceiver receives an Intent broadcast.
    // Checks whether the intent's action is TOAST_ACTION. If it is, the
    // widget displays a Toast message for the current item.
    override fun onReceive(context: Context, intent: Intent) {
        val mgr: AppWidgetManager = AppWidgetManager.getInstance(context)
        if (intent.action == TOAST_ACTION) {
            val appWidgetId: Int = intent.getIntExtra(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID
            )
            // EXTRA_ITEM represents a custom value provided by the Intent
            // passed to the setOnClickFillInIntent() method to indicate the
            // position of the clicked item. See StackRemoteViewsFactory in
            // Set the fill-in Intent for details.
            val viewIndex: Int = intent.getIntExtra(EXTRA_ITEM, 0)
            Toast.makeText(context, "Touched view $viewIndex", Toast.LENGTH_SHORT).show()
        }
        super.onReceive(context, intent)
    }

    override fun onUpdate(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetIds: IntArray
    ) {
        // Update each of the widgets with the remote adapter.
        appWidgetIds.forEach { appWidgetId ->

            // Sets up the intent that points to the StackViewService that
            // provides the views for this collection.
            val intent = Intent(context, StackWidgetService::class.java).apply {
                putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                // When intents are compared, the extras are ignored, so embed
                // the extra sinto the data so that the extras are not ignored.
                data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
            }
            val rv = RemoteViews(context.packageName, R.layout.widget_layout).apply {
                setRemoteAdapter(R.id.stack_view, intent)

                // The empty view is displayed when the collection has no items.
                // It must be a sibling of the collection view.
                setEmptyView(R.id.stack_view, R.id.empty_view)
            }

            // This section makes it possible for items to have individualized
            // behavior. It does this by setting up a pending intent template.
            // Individuals items of a collection can't set up their own pending
            // intents. Instead, the collection as a whole sets up a pending
            // intent template, and the individual items set a fillInIntent
            // to create unique behavior on an item-by-item basis.
            val toastPendingIntent: PendingIntent = Intent(
                    context,
                    StackWidgetProvider::class.java
            ).run {
                // Set the action for the intent.
                // When the user touches a particular view, it has the effect of
                // broadcasting TOAST_ACTION.
                action = TOAST_ACTION
                putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))

                PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_UPDATE_CURRENT)
            }
            rv.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent)

            appWidgetManager.updateAppWidget(appWidgetId, rv)
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds)
    }
}

Java

public class StackWidgetProvider extends AppWidgetProvider {
    public static final String TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION";
    public static final String EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM";

    ...

    // Called when the BroadcastReceiver receives an Intent broadcast.
    // Checks whether the intent's action is TOAST_ACTION. If it is, the
    // widget displays a Toast message for the current item.
    @Override
    public void onReceive(Context context, Intent intent) {
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        if (intent.getAction().equals(TOAST_ACTION)) {
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
            // EXTRA_ITEM represents a custom value provided by the Intent
            // passed to the setOnClickFillInIntent() method to indicate the
            // position of the clicked item. See StackRemoteViewsFactory in
            // Set the fill-in Intent for details.
            int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);
            Toast.makeText(context, "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();
        }
        super.onReceive(context, intent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // Update each of the widgets with the remote adapter.
        for (int i = 0; i < appWidgetIds.length; ++i) {

            // Sets up the intent that points to the StackViewService that
            // provides the views for this collection.
            Intent intent = new Intent(context, StackWidgetService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            // When intents are compared, the extras are ignored, so embed
            // the extras into the data so that the extras are not
            // ignored.
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            rv.setRemoteAdapter(appWidgetIds[i], R.id.stack_view, intent);

            // The empty view is displayed when the collection has no items. It
            // must be a sibling of the collection view.
            rv.setEmptyView(R.id.stack_view, R.id.empty_view);

            // This section makes it possible for items to have individualized
            // behavior. It does this by setting up a pending intent template.
            // Individuals items of a collection can't set up their own pending
            // intents. Instead, the collection as a whole sets up a pending
            // intent template, and the individual items set a fillInIntent
            // to create unique behavior on an item-by-item basis.
            Intent toastIntent = new Intent(context, StackWidgetProvider.class);
            // Set the action for the intent.
            // When the user touches a particular view, it has the effect of
            // broadcasting TOAST_ACTION.
            toastIntent.setAction(StackWidgetProvider.TOAST_ACTION);
            toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
            rv.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }
}

Imposta l'intent di compilazione

Il RemoteViewsFactory deve impostare un intent di compilazione per ciascun elemento nell' . In questo modo è possibile distinguere la singola azione al clic di un determinato elemento. L'intento di riempimento viene quindi combinato con PendingIntent modello per determinare l'intent finale che viene eseguito quando l'elemento viene toccato.

Kotlin

private const val REMOTE_VIEW_COUNT: Int = 10

class StackRemoteViewsFactory(
        private val context: Context,
        intent: Intent
) : RemoteViewsService.RemoteViewsFactory {

    private lateinit var widgetItems: List<WidgetItem>
    private val appWidgetId: Int = intent.getIntExtra(
            AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID
    )

    override fun onCreate() {
        // In onCreate(), set up any connections or cursors to your data source.
        // Heavy lifting, such as downloading or creating content, must be
        // deferred to onDataSetChanged() or getViewAt(). Taking more than 20
        // seconds on this call results in an ANR.
        widgetItems = List(REMOTE_VIEW_COUNT) { index -> WidgetItem("$index!") }
        ...
    }
    ...

    override fun getViewAt(position: Int): RemoteViews {
        // Construct a remote views item based on the widget item XML file
        // and set the text based on the position.
        return RemoteViews(context.packageName, R.layout.widget_item).apply {
            setTextViewText(R.id.widget_item, widgetItems[position].text)

            // Set a fill-intent to fill in the pending intent template.
            // that is set on the collection view in StackWidgetProvider.
            val fillInIntent = Intent().apply {
                Bundle().also { extras ->
                    extras.putInt(EXTRA_ITEM, position)
                    putExtras(extras)
                }
            }
            // Make it possible to distinguish the individual on-click
            // action of a given item.
            setOnClickFillInIntent(R.id.widget_item, fillInIntent)
            ...
        }
    }
    ...
}

Java

public class StackWidgetService extends RemoteViewsService {
    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
    }
}

class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
    private static final int count = 10;
    private List<WidgetItem> widgetItems = new ArrayList<WidgetItem>();
    private Context context;
    private int appWidgetId;

    public StackRemoteViewsFactory(Context context, Intent intent) {
        this.context = context;
        appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    // Initialize the data set.
    public void onCreate() {
        // In onCreate(), set up any connections or cursors to your data
        // source. Heavy lifting, such as downloading or creating
        // content, must be deferred to onDataSetChanged() or
        // getViewAt(). Taking more than 20 seconds on this call results
        // in an ANR.
        for (int i = 0; i < count; i++) {
            widgetItems.add(new WidgetItem(i + "!"));
        }
        ...
    }

    // Given the position (index) of a WidgetItem in the array, use the
    // item's text value in combination with the widget item XML file to
    // construct a RemoteViews object.
    public RemoteViews getViewAt(int position) {
        // Position always ranges from 0 to getCount() - 1.

        // Construct a RemoteViews item based on the widget item XML
        // file and set the text based on the position.
        RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_item);
        rv.setTextViewText(R.id.widget_item, widgetItems.get(position).text);

        // Set a fill-intent to fill in the pending
        // intent template that is set on the collection view in
        // StackWidgetProvider.
        Bundle extras = new Bundle();
        extras.putInt(StackWidgetProvider.EXTRA_ITEM, position);
        Intent fillInIntent = new Intent();
        fillInIntent.putExtras(extras);
        // Make it possible to distinguish the individual on-click
        // action of a given item.
        rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent);

        // Return the RemoteViews object.
        return rv;
    }
    ...
}

Mantieni aggiornati i dati della raccolta

La Figura 2 illustra il flusso di aggiornamento in un widget che utilizza le raccolte. Mostra in che modo il codice del widget interagisce con RemoteViewsFactory e come puoi attiva gli aggiornamenti:

Figura 2. Interazione con RemoteViewsFactory durante gli aggiornamenti.

I widget che utilizzano le raccolte possono fornire agli utenti contenuti aggiornati. Per Ad esempio, il widget Gmail offre agli utenti un'istantanea della posta in arrivo. Per fare in modo che possibile, attiva RemoteViewsFactory e la vista raccolta per recuperare e visualizzare nuovi dati.

A questo scopo, utilizza AppWidgetManager per chiamare notifyAppWidgetViewDataChanged(). Questa chiamata determina un callback all'oggetto RemoteViewsFactory onDataSetChanged() che ti consente di recuperare nuovi dati.

Puoi eseguire operazioni ad alta intensità di elaborazione in modo sincrono all'interno Chiamata di onDataSetChanged(). Ti garantiamo che questa chiamata verrà completata prima che i dati dei metadati o della vista vengano recuperati da RemoteViewsFactory. Tu può anche eseguire operazioni ad alta intensità di elaborazione all'interno di getViewAt() . Se questa chiamata richiede molto tempo, la visualizzazione in fase di caricamento, specificata dal RemoteViewsFactory oggetto getLoadingView() : viene mostrato nella posizione corrispondente della visualizzazione raccolta fino a quando non viene restituito.

Utilizzare RemoteCollectionItems per trasmettere direttamente una raccolta

Android 12 (livello API 31) aggiunge setRemoteAdapter(int viewId, RemoteViews.RemoteCollectionItems items) che consente alla tua app di trasmettere direttamente una raccolta durante la compilazione di un vista raccolta. Se configuri l'adattatore con questo metodo, non è necessario implementa un RemoteViewsFactory e non devi chiamare notifyAppWidgetViewDataChanged().

Oltre a semplificare la compilazione dell'adattatore, questo approccio rimuove la latenza per il completamento di nuovi elementi quando gli utenti scorrono l'elenco verso il basso per scoprire un nuovo oggetto. Questo approccio per impostare l'adattatore è preferibile, purché l'insieme di elementi della raccolta è relativamente piccolo. Tuttavia, ad esempio, non funziona bene se la raccolta contiene numerosi Bitmaps che possono essere passato a setImageViewBitmap.

Se la raccolta non usa un insieme costante di layout, ovvero sono presenti solo qualche volta; usa setViewTypeCount per specificare numero massimo di layout univoci che la raccolta può contenere. Ciò consente l'adattatore può essere riutilizzato negli aggiornamenti del widget dell'app.

Ecco un esempio di come implementare le raccolte RemoteViews semplificate.

Kotlin

val itemLayouts = listOf(
        R.layout.item_type_1,
        R.layout.item_type_2,
        ...
)

remoteView.setRemoteAdapter(
        R.id.list_view,
        RemoteViews.RemoteCollectionItems.Builder()
            .addItem(/* id= */ ID_1, RemoteViews(context.packageName, R.layout.item_type_1))
            .addItem(/* id= */ ID_2, RemoteViews(context.packageName, R.layout.item_type_2))
            ...
            .setViewTypeCount(itemLayouts.count())
            .build()
)

Java

List<Integer> itemLayouts = Arrays.asList(
    R.layout.item_type_1,
    R.layout.item_type_2,
    ...
);

remoteView.setRemoteAdapter(
    R.id.list_view,
    new RemoteViews.RemoteCollectionItems.Builder()
        .addItem(/* id= */ ID_1, new RemoteViews(context.getPackageName(), R.layout.item_type_1))
        .addItem(/* id= */ ID_2, new RemoteViews(context.getPackageName(), R.layout.item_type_2))
        ...
        .setViewTypeCount(itemLayouts.size())
        .build()
);