I widget raccolta sono specializzati nella visualizzazione di molti elementi dello stesso tipo, ad esempio raccolte di immagini di un'app Galleria, articoli di un'app di notizie o messaggi di un'app di comunicazione. I widget per le raccolte si concentrano in genere su due casi d'uso: sfogliare la raccolta e aprire un elemento della raccolta nella sua visualizzazione dettagliata. I widget della raccolta possono scorrere in verticale.
Questi widget utilizzano RemoteViewsService
per visualizzare le raccolte supportate da dati remoti, ad esempio quelli provenienti da un fornitore di contenuti. Il widget presenta i dati utilizzando uno dei seguenti tipi di viste, note come viste di raccolta:
ListView
- Una visualizzazione che mostra gli elementi in un elenco a scorrimento verticale.
GridView
- Una visualizzazione che mostra gli elementi in una griglia a scorrimento bidimensionale.
StackView
- Una visualizzazione a schede impilate, un po' come un rolodex, dove l'utente può scorrere la scheda anteriore verso l'alto o verso il basso per vedere rispettivamente la scheda precedente o successiva.
AdapterViewFlipper
- Un semplice
ViewAnimator
basato su adattatore che si anima tra due o più visualizzazioni. Viene visualizzato un solo bambino alla volta.
Poiché queste viste raccolta mostrano raccolte supportate da dati remoti, utilizzano un elemento Adapter
per associare l'interfaccia
utente ai propri dati. Un Adapter
associa singoli elementi da un set di dati a singoli oggetti View
.
Inoltre, poiché queste visualizzazioni raccolte sono supportate da adattatori, il framework Android deve includere un'architettura aggiuntiva per supportarne l'utilizzo nei widget. Nel contesto di un widget, Adapter
viene sostituito da RemoteViewsFactory
, ovvero un wrapper sottile che circonda l'interfaccia Adapter
. Quando viene richiesto un
elemento specifico nella raccolta, RemoteViewsFactory
crea e restituisce
l'elemento per la raccolta come
oggetto RemoteViews
. Per includere una
visualizzazione raccolta nel widget, implementa RemoteViewsService
e
RemoteViewsFactory
.
RemoteViewsService
è un servizio che consente a un adattatore remoto di richiedere
RemoteViews
oggetti. RemoteViewsFactory
è un'interfaccia per un adattatore tra una vista raccolta, ad esempio ListView
, GridView
e StackView
, e i dati sottostanti per quella vista. Dall'esempio di StackWidget
, ecco un esempio di codice boilerplate per implementare questo servizio e questa 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 di codice in questa sezione sono tratti dal campione StackWidget
:
Questo esempio è costituito da uno stack di dieci visualizzazioni che mostrano i valori da zero a nove. Il widget di esempio presenta i seguenti comportamenti principali:
L'utente può inclinare verticalmente la vista dall'alto nel widget per passare a quella successiva o precedente. Si tratta di un comportamento integrato di
StackView
.Senza alcuna interazione da parte dell'utente, il widget avanza automaticamente in sequenza, come in una presentazione. Ciò è dovuto all'impostazione
android:autoAdvanceViewId="@id/stack_view"
nel fileres/xml/stackwidgetinfo.xml
. 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 il messaggio
Toast
"Vista toccata n", dove n è l'indice (posizione) della vista toccata. Per ulteriori discussioni su come implementare i comportamenti, consulta la sezione Aggiungere comportamento a singoli elementi.
Implementare widget con raccolte
Per implementare un widget con raccolte, segui la procedura per implementare qualsiasi widget, seguita da alcuni passaggi aggiuntivi: modifica il manifest, aggiungi una vista raccolta al layout del widget e modifica la sottoclasse AppWidgetProvider
.
Manifest per widget con raccolte
Oltre ai requisiti elencati nella sezione Dichiarare un widget nel file manifest, devi consentire ai widget con raccolte di essere associati al tuo RemoteViewsService
. Per farlo, dichiara il servizio nel file manifest con l'autorizzazione BIND_REMOTEVIEWS
.
Ciò impedisce ad altre applicazioni di accedere liberamente ai dati del tuo widget.
Ad esempio, quando crei un widget che utilizza RemoteViewsService
per completare 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 di
RemoteViewsService
.
Layout per widget con raccolte
Il requisito principale per il file XML del layout del widget è che includa una delle viste raccolta: ListView
, GridView
, StackView
o AdapterViewFlipper
. Ecco il file widget_layout.xml
per l'esempio di StackWidget
:
<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 affini della vista raccolta per cui la vista vuota rappresenta lo stato vuoto.
Oltre al file di layout per l'intero widget, crea un altro file di layout che definisca il layout di ogni elemento della raccolta, ad esempio un layout per ogni libro in una raccolta di libri. L'esempio StackWidget
ha un solo file di layout degli elementi, widget_item.xml
, poiché tutti gli elementi utilizzano lo stesso layout.
Classe AppWidgetProvider per widget con raccolte
Come con i widget normali, la maggior parte del codice nella
sottoclasse AppWidgetProvider
in genere va in
onUpdate()
.
La differenza principale nella tua implementazione per onUpdate()
quando crei un
widget con raccolte è che devi chiamare
setRemoteAdapter()
. Questo indica alla vista raccolta dove trovare i dati.
L'oggetto RemoteViewsService
può quindi restituire l'implementazione di RemoteViewsFactory
e il widget può fornire i dati appropriati. Quando chiami questo metodo, trasmetti un intent che punti all'implementazione di RemoteViewsService
e l'ID widget che specifica il widget da aggiornare.
Ad esempio, ecco come l'esempio StackWidget
implementa il metodo di callback onUpdate()
per impostare RemoteViewsService
come adattatore remoto per la raccolta dei 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 dati
Come descritto in questa pagina, la sottoclasse RemoteViewsService
fornisce il valore RemoteViewsFactory
utilizzato per completare la visualizzazione della raccolta remota.
In particolare, esegui questi passaggi:
Sottoclasse
RemoteViewsService
.RemoteViewsService
è il servizio tramite il quale un adattatore remoto può richiedereRemoteViews
.Nella sottoclasse
RemoteViewsService
, includi una classe che implementa l'interfacciaRemoteViewsFactory
.RemoteViewsFactory
è un'interfaccia per un adattatore tra una vista raccolta remota, comeListView
,GridView
eStackView
, e i dati sottostanti per quella vista. L'implementazione è responsabile della creazione di un oggettoRemoteViews
per ogni elemento del set di dati. Questa interfaccia è un wrapper sottile che circondaAdapter
.
Non puoi fare affidamento su una singola istanza del tuo servizio o sui dati che contiene. Non archiviare dati in RemoteViewsService
a meno che non siano statici. Se
vuoi che i dati del widget rimangano invariati, l'approccio migliore è utilizzare una
ContentProvider
i cui dati
permangono oltre il ciclo di vita del processo. Ad esempio, il widget di un negozio di alimentari può archiviare lo stato di ogni articolo dell'elenco della spesa in una posizione persistente come un database SQL.
Il contenuto principale dell'implementazione RemoteViewsService
è il relativo RemoteViewsFactory
, descritto nella sezione seguente.
Interfaccia RemoteViewsFactory
La classe personalizzata che implementa l'interfaccia RemoteViewsFactory
fornisce al widget i dati per gli elementi della sua raccolta. A questo scopo, combina il file di layout XML dell'elemento del widget con un'origine dati. L'origine dati può essere qualsiasi cosa, da un database a un array semplice. Nel campione StackWidget
, l'origine dati è un array di WidgetItems
. L'RemoteViewsFactory
funziona come adattatore per incollare i dati alla vista raccolta remota.
I due metodi più importanti da implementare per la tua
sottoclasse RemoteViewsFactory
sono
onCreate()
e
getViewAt()
.
Il sistema chiama onCreate()
quando crea i dati di fabbrica per la prima volta.
Qui puoi configurare le connessioni o i cursori all'origine dati. Ad esempio, l'esempio StackWidget
utilizza onCreate()
per inizializzare un array di oggetti WidgetItem
. Quando il widget è attivo, il sistema accede a questi oggetti utilizzando la loro posizione di indice nell'array e visualizza il testo che contengono.
Ecco un estratto dall'implementazione RemoteViewsFactory
dell'esempio StackWidget
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
corrispondente ai dati nel valore position
specificato nel set di dati. Ecco
un estratto dall'implementazione 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; }
Aggiungere un comportamento ai singoli elementi
Le sezioni precedenti mostrano come associare i dati alla raccolta di widget. E se volessi aggiungere un comportamento dinamico ai singoli elementi nella visualizzazione raccolta?
Come descritto in Gestire gli eventi con la
classe onUpdate()
, in genere utilizzi
setOnClickPendingIntent()
per impostare il comportamento di clic di un oggetto, ad esempio per
causare un pulsante per avviare una Activity
. Tuttavia, 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, ma non nelle singole voci dell'elenco.
Per aggiungere il comportamento dei clic a singoli elementi di una raccolta, utilizza invece setOnClickFillInIntent()
. Ciò comporta la configurazione di un modello di intent in attesa per la visualizzazione della raccolta e poi l'impostazione di un intent di compilazione per ogni elemento nella raccolta tramite RemoteViewsFactory
.
In questa sezione viene utilizzato il campione StackWidget
per descrivere come aggiungere il comportamento ai singoli elementi. Nell'esempio StackWidget
, se l'utente tocca la vista dall'alto, il widget mostra il messaggio Toast
"Vista toccata n", dove n è l'indice (posizione) della vista toccata. Ecco come funziona:
La
StackWidgetProvider
, una sottoclasseAppWidgetProvider
, crea un intent in attesa con un'azione personalizzata denominataTOAST_ACTION
.Quando l'utente tocca una visualizzazione, l'intent si attiva e trasmette
TOAST_ACTION
.Questo broadcast viene intercettato dal metodo
onReceive()
della classeStackWidgetProvider
e il widget mostra il messaggioToast
relativo alla visualizzazione toccata. I dati per gli elementi della raccolta vengono forniti daRemoteViewsFactory
tramiteRemoteViewsService
.
Configurare il modello di intent in attesa
StackWidgetProvider
(una
sottoclasse AppWidgetProvider
)
configura un intent in attesa. I singoli elementi di una raccolta non possono configurare i propri intent in attesa. Invece, l'intera raccolta configura un modello di intent in attesa e i singoli elementi impostano un intent di compilazione per creare un comportamento unico per ogni singolo elemento.
Questa classe riceve anche la trasmissione inviata quando l'utente tocca una visualizzazione. Elabora questo evento nel suo metodo onReceive()
. Se l'azione dell'intent
è TOAST_ACTION
, il widget mostra un messaggio Toast
per la
vista corrente.
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
RemoteViewsFactory
deve impostare un intent di compilazione per ogni elemento nella
raccolta. Ciò consente di distinguere la singola azione al clic di un determinato elemento. L'intent di compilazione viene quindi combinato con il modello PendingIntent
per determinare l'intent finale che viene eseguito quando viene toccato l'elemento.
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
come il codice del widget interagisce con RemoteViewsFactory
e come
puoi attivare gli aggiornamenti:
I widget che utilizzano le raccolte possono fornire agli utenti contenuti aggiornati. Ad esempio, il widget Gmail offre agli utenti un'istantanea della loro Posta in arrivo. Per rendere possibile questo
operazione, attiva RemoteViewsFactory
e la vista raccolta per recuperare e
visualizzare nuovi dati.
A questo scopo, utilizza AppWidgetManager
per chiamare notifyAppWidgetViewDataChanged()
. Questa chiamata genera un callback al metodo
onDataSetChanged()
dell'oggetto RemoteViewsFactory
, che ti permette di recuperare tutti i nuovi dati.
Puoi eseguire operazioni ad alta intensità di elaborazione in modo sincrono all'interno del callback onDataSetChanged()
. Hai la certezza che questa chiamata sia completata prima che i metadati o i dati delle visualizzazioni vengano recuperati da RemoteViewsFactory
. Con il metodo getViewAt()
puoi anche eseguire operazioni ad alta intensità di elaborazione. Se questa chiamata richiede molto tempo, la visualizzazione di caricamento, specificata dal metodo getLoadingView()
dell'oggetto RemoteViewsFactory
, viene mostrata nella posizione corrispondente della vista raccolta fino a quando non viene restituita.
Utilizza RemoteCollectionItems per trasmettere direttamente una raccolta
Android 12 (livello API 31) aggiunge il metodo setRemoteAdapter(int viewId,
RemoteViews.RemoteCollectionItems
items)
, che consente all'app di trasmettere una raccolta direttamente quando compili una visualizzazione raccolta. Se imposti l'adattatore utilizzando questo metodo, non è necessario
implementare un RemoteViewsFactory
e non devi chiamare
notifyAppWidgetViewDataChanged()
.
Oltre a semplificare la compilazione dell'adattatore, questo approccio rimuove anche la latenza per il completamento di nuovi elementi quando gli utenti scorrono l'elenco verso il basso per scoprire un nuovo elemento. Questo approccio per impostare l'adattatore è preferibile a condizione
che l'insieme di elementi della raccolta sia relativamente piccolo. Tuttavia, ad esempio, questo approccio non funziona bene se la raccolta contiene numerosi Bitmaps
che vengono passati a setImageViewBitmap
.
Se la raccolta non utilizza un insieme costante di layout, ovvero se alcuni
elementi sono presenti solo occasionalmente, utilizza setViewTypeCount
per specificare il
numero massimo di layout univoci che la raccolta può contenere. In questo modo l'adattatore può essere riutilizzato per tutti gli aggiornamenti al 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() );