שימוש בווידג'טים של אוספים

אנסה לכתוב
‫Jetpack Compose היא ערכת הכלים המומלצת לבניית ממשק משתמש ל-Android. איך יוצרים ווידג'טים באמצעות ממשקי API בסגנון Compose

ווידג'טים של אוספים מתמחים בהצגת הרבה רכיבים מאותו סוג, כמו אוספים של תמונות מאפליקציית גלריה, מאמרים מאפליקציית חדשות או הודעות מאפליקציית תקשורת. ווידג'טים של אוספים מתמקדים בדרך כלל בשני תרחישי שימוש: עיון באוסף ופתיחת רכיב מהאוסף לתצוגת הפרטים שלו. אפשר לגלול אנכית בווידג'טים של קולקציות.

הווידג'טים האלה משתמשים ב-RemoteViewsService כדי להציג אוספים שמגובים על ידי נתונים מרחוק, למשל מספק תוכן. הווידג'ט מציג את הנתונים באמצעות אחד מסוגי התצוגה הבאים, שנקראים תצוגות אוסף:

ListView
תצוגה שבה הפריטים מוצגים ברשימה שאפשר לגלול בה אנכית.
GridView
תצוגה שבה הפריטים מוצגים ברשת דו-ממדית שאפשר לגלול בה.
StackView
תצוגת כרטיסים מוערמים – בדומה לכרטיסיות מסתובבות – שבה המשתמש יכול להחליק את הכרטיס הקדמי למעלה או למטה כדי לראות את הכרטיס הקודם או הבא, בהתאמה.
AdapterViewFlipper
אנימציה פשוטה עם תמיכה במתאם ViewAnimator שמתבצעת בין שתי תצוגות או יותר. בכל פעם מוצג רק ילד אחד.

תצוגות האוסף האלה מציגות אוספים שמגובים בנתונים מרוחקים, ולכן הן משתמשות ב-Adapter כדי לקשר את ממשק המשתמש שלהן לנתונים. Adapter קושר בין פריטים ספציפיים מתוך קבוצת נתונים לבין אובייקטים ספציפיים של View.

ומכיוון שתצוגות האוסף האלה מגובות על ידי מתאמים, מסגרת Android צריכה לכלול ארכיטקטורה נוספת כדי לתמוך בשימוש בהן בווידג'טים. בהקשר של ווידג'ט, Adapter מוחלף ב-RemoteViewsFactory, שהוא עטיפה דקה סביב הממשק Adapter. כשמבקשים פריט ספציפי באוסף, RemoteViewsFactory יוצר ומחזיר את הפריט לאוסף כאובייקט RemoteViews. כדי לכלול תצוגת אוסף בווידג'ט, צריך להטמיע את RemoteViewsService ואת RemoteViewsFactory.

RemoteViewsService הוא שירות שמאפשר למתאם מרוחק לבקש אובייקטים של RemoteViews. ‫RemoteViewsFactory הוא ממשק למתאם בין תצוגת אוסף – כמו ListView, GridView ו-StackView – לבין הנתונים הבסיסיים של התצוגה הזו. בדוגמה הבאה מופיע קוד ה-boilerplate להטמעה של השירות והממשק האלה, מתוך StackWidgetהדוגמה:

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.

}

אפליקציה לדוגמה

קטעי הקוד בקטע הזה נלקחו גם הם מהדוגמה StackWidget:

איור 1.StackWidget.

הדוגמה הזו מורכבת מערימה של עשרה תצוגות שמציגות את הערכים אפס עד תשע. הווידג'ט לדוגמה פועל בדרכים העיקריות הבאות:

  • המשתמש יכול להחליק אנכית את התצוגה העליונה בווידג'ט כדי להציג את התצוגה הבאה או הקודמת. זו התנהגות מובנית של StackView.

  • ללא אינטראקציה עם המשתמש, הווידג'ט עובר באופן אוטומטי בין התצוגות שלו ברצף, כמו מצגת. הסיבה לכך היא ההגדרה android:autoAdvanceViewId="@id/stack_view" בקובץ res/xml/stackwidgetinfo.xml. ההגדרה הזו חלה על מזהה התצוגה המפורטת, שבמקרה הזה הוא מזהה התצוגה המפורטת של תצוגת הערימה.

  • אם המשתמש מקיש על התצוגה העליונה, בווידג'ט מוצגת ההודעה Toast Touched view n (התצוגה n הוקשה), כאשר n הוא האינדקס (המיקום) של התצוגה שהוקשה. מידע נוסף על הטמעה של התנהגויות זמין בקטע הוספת התנהגות לפריטים ספציפיים.

הטמעה של ווידג'טים באמצעות אוספים

כדי להטמיע ווידג'ט עם אוספים, פועלים לפי ההליך להטמעה של כל ווידג'ט, ואז מבצעים כמה שלבים נוספים: משנים את המניפסט, מוסיפים תצוגת אוסף לפריסת הווידג'ט ומשנים את מחלקת המשנה AppWidgetProvider.

מניפסט לווידג'טים עם אוספים

בנוסף לדרישות שמפורטות במאמר הצהרה על ווידג'ט במניפסט, צריך לאפשר לווידג'טים עם אוספים להיקשר ל-RemoteViewsService. כדי לעשות את זה, צריך להצהיר על השירות בקובץ המניפסט עם ההרשאה BIND_REMOTEVIEWS. כך אפליקציות אחרות לא יוכלו לגשת לנתונים של הווידג'ט שלכם באופן חופשי.

לדוגמה, כשיוצרים ווידג'ט שמשתמש ב-RemoteViewsService כדי לאכלס תצוגת אוסף, יכול להיות שרשומה במניפסט תיראה כך:

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

בדוגמה הזו, android:name="MyWidgetService" מתייחס למחלקת המשנה שלכם של RemoteViewsService.

פריסה לווידג'טים עם אוספים

הדרישה העיקרית מקובץ ה-XML של פריסת הווידג'ט היא שהוא יכלול את אחד מהתצוגות של האוסף: ListView, GridView, StackView או AdapterViewFlipper. קובץ widget_layout.xml לדוגמה של 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>

חשוב לזכור שתצוגות ריקות צריכות להיות באותה רמה של תצוגת האוסף שעבורה התצוגה הריקה מייצגת מצב ריק.

בנוסף לקובץ הפריסה של הווידג'ט כולו, יוצרים עוד קובץ פריסה שמגדיר את הפריסה של כל פריט באוסף – לדוגמה, פריסה לכל ספר באוסף ספרים. בדוגמה StackWidget יש רק קובץ פריסת פריטים אחד, widget_item.xml, כי כל הפריטים משתמשים באותה פריסה.

המחלקות AppWidgetProvider לווידג'טים עם אוספים

בדומה לווידג'טים רגילים, רוב הקוד בתת-המחלקות AppWidgetProvider בדרך כלל מופיע ב-onUpdate(). ההבדל העיקרי בהטמעה של onUpdate() כשיוצרים ווידג'ט עם אוספים הוא שצריך להפעיל את setRemoteAdapter(). הפעולה הזו מציינת לתצוגת האוסף מאיפה לקבל את הנתונים. לאחר מכן, RemoteViewsService יכול להחזיר את ההטמעה של RemoteViewsFactory, והווידג'ט יכול להציג את הנתונים המתאימים. כשמפעילים את השיטה הזו, מעבירים intent שמפנה להטמעה של RemoteViewsService ואת מזהה הווידג'ט שמציין את הווידג'ט לעדכון.

לדוגמה, כך מיושמת הדוגמה StackWidget של שיטת הקריאה החוזרת onUpdate() כדי להגדיר את RemoteViewsService כמתאם המרוחק לאוסף הווידג'טים:

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);
}

שמירת נתונים

כמו שמתואר בדף הזה, מחלקת המשנה RemoteViewsService מספקת את RemoteViewsFactory שמשמש לאכלוס תצוגת האוסף המרוחק.

צריך לבצע את הפעולות הבאות:

  1. קטגוריית משנה RemoteViewsService. ‫RemoteViewsService הוא השירות שדרכו מתאם מרוחק יכול לבקש RemoteViews.

  2. במחלקת המשנה RemoteViewsService, כוללים מחלקה שמטמיעה את הממשק RemoteViewsFactory. ‫RemoteViewsFactory הוא ממשק למתאם בין תצוגת אוסף מרוחקת – כמו ListView,‏ GridView, ‏ StackView – לבין הנתונים הבסיסיים של התצוגה הזו. ההטמעה שלכם אחראית ליצירת אובייקט RemoteViews לכל פריט במערך הנתונים. הממשק הזה הוא מעטפת דקה סביב Adapter.

אי אפשר להסתמך על מופע יחיד של השירות או על נתונים שהוא מכיל כדי לשמור על נתונים. אל תאחסנו נתונים ב-RemoteViewsService אלא אם הם סטטיים. אם רוצים שהנתונים של הווידג'ט יישמרו, הגישה הכי טובה היא להשתמש בContentProvider שהנתונים שלו נשמרים גם אחרי סיום התהליך. לדוגמה, בווידג'ט של חנות מכולת אפשר לאחסן את המצב של כל פריט ברשימת הקניות במיקום קבוע, כמו מסד נתונים של SQL.

התוכן העיקרי של הטמעת RemoteViewsService הוא RemoteViewsFactory, שמתואר בקטע הבא.

הממשק RemoteViewsFactory

המחלקה המותאמת אישית שמטמיעה את הממשק RemoteViewsFactory מספקת לווידג'ט את הנתונים של הפריטים באוסף שלו. כדי לעשות את זה, הוא משלב את קובץ הפריסה של פריט הווידג'ט בפורמט XML עם מקור נתונים. מקור הנתונים יכול להיות כל דבר, ממסד נתונים ועד למערך פשוט. StackWidget בדוגמה, מקור הנתונים הוא מערך של WidgetItems. הפונקציה RemoteViewsFactory פועלת כמתאם כדי להצמיד את הנתונים לתצוגת האוסף המרוחקת.

שתי השיטות הכי חשובות שצריך להטמיע עבור מחלקת המשנה RemoteViewsFactory הן onCreate() ו-getViewAt().

המערכת קוראת ל-onCreate() כשיוצרים את המפעל בפעם הראשונה. כאן מגדירים חיבורים או סמנים למקור הנתונים. לדוגמה, בדוגמה StackWidget נעשה שימוש ב-onCreate() כדי לאתחל מערך של אובייקטים מסוג WidgetItem. כשהווידג'ט פעיל, המערכת ניגשת לאובייקטים האלה באמצעות מיקום האינדקס שלהם במערך ומציגה את הטקסט שהם מכילים.

קטע מתוך ההטמעה של StackWidgetהדוגמהRemoteViewsFactory שמציג חלקים מהשיטה 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 + "!"));
        }
        ...
    }
...

השיטה RemoteViewsFactory getViewAt() מחזירה אובייקט RemoteViews שתואם לנתונים במיקום position שצוין במערך הנתונים. קטע מתוך ההטמעה של StackWidget בדוגמה RemoteViewsFactory:

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;
}

הוספת התנהגות לפריטים ספציפיים

בקטעים הקודמים מוסבר איך לקשר את הנתונים לאוסף הווידג'טים. אבל מה אם רוצים להוסיף התנהגות דינמית לפריטים בודדים בתצוגת האוסף?

כפי שמתואר במאמר טיפול באירועים באמצעות המחלקה onUpdate(), בדרך כלל משתמשים ב-setOnClickPendingIntent() כדי להגדיר את התנהגות הקליק של אובייקט – למשל, כדי לגרום ללחצן להפעיל Activity. אבל אסור להשתמש בגישה הזו בתצוגות של ילדים בפריט אוסף בודד. לדוגמה, אפשר להשתמש ב-setOnClickPendingIntent() כדי להגדיר לחצן גלובלי בווידג'ט של Gmail שמפעיל את האפליקציה, אבל לא בפריטים בודדים ברשימה.

במקום זאת, כדי להוסיף התנהגות קליקים לפריטים ספציפיים באוסף, משתמשים בתג setOnClickFillInIntent(). כדי לעשות את זה, צריך להגדיר תבנית של PendingIntent לתצוגת האוסף, ואז להגדיר Fill-in Intent לכל פריט באוסף באמצעות RemoteViewsFactory.

בקטע הזה אנחנו משתמשים בדוגמה StackWidget כדי להסביר איך מוסיפים התנהגות לפריטים בודדים. בדוגמה StackWidget, אם המשתמש מקיש על התצוגה העליונה, הווידג'ט מציג את ההודעה Toast 'הוקשה תצוגה n', כאשר n הוא האינדקס (המיקום) של התצוגה שהוקשה. כך זה עובד:

  • ה-StackWidgetProvider – מחלקת משנה של AppWidgetProvider – יוצרת כוונת הפעלה בהמתנה עם פעולה מותאמת אישית בשם TOAST_ACTION.

  • כשמשתמש מקיש על תצוגה, האירוע intent מופעל ומשודר TOAST_ACTION.

  • השידור הזה נקטע על ידי השיטה onReceive() של המחלקה StackWidgetProvider, והווידג'ט מציג את ההודעה Toast לתצוגה שהמשתמש נגע בה. הנתונים של הפריטים באוסף מסופקים על ידי RemoteViewsFactory דרך RemoteViewsService.

הגדרת תבנית של כוונת משתמש בהמתנה

ה-StackWidgetProvider (מחלקת משנה של AppWidgetProvider) מגדיר PendingIntent. אי אפשר להגדיר כוונות בהמתנה לפריטים ספציפיים באוסף. במקום זאת, האוסף כולו מגדיר תבנית של כוונה בהמתנה, והפריטים הבודדים מגדירים כוונה למילוי כדי ליצור התנהגות ייחודית על בסיס פריט-לפריט.

המחלקות האלה מקבלות גם את השידור שנשלח כשהמשתמש נוגע בתצוגה. הוא מעבד את האירוע הזה בשיטה onReceive() שלו. אם הפעולה של הכוונה היא TOAST_ACTION, בווידג'ט מוצגת הודעה Toast לגבי התצוגה הנוכחית.

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);
    }
}

הגדרת כוונת המשתמש להשלמת פרטים

ב-RemoteViewsFactory צריך להגדיר כוונת מילוי לכל פריט באוסף. כך אפשר להבחין בין הפעולות השונות שמתבצעות בלחיצה על פריט מסוים. הכוונה להשלמת המידע משולבת עם תבנית PendingIntent כדי לקבוע את הכוונה הסופית שמופעלת כשמקישים על הפריט.

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;
    }
    ...
}

שמירה על עדכניות הנתונים באוסף

איור 2 מציג את תהליך העדכון בווידג'ט שמשתמש באוספים. בדוגמה הזו אפשר לראות איך קוד הווידג'ט מתקשר עם RemoteViewsFactory ואיך אפשר להפעיל עדכונים:

איור 2. אינטראקציה עם RemoteViewsFactory במהלך עדכונים.

ווידג'טים שמשתמשים בקולקציות יכולים לספק למשתמשים תוכן עדכני. לדוגמה, הווידג'ט של Gmail מאפשר למשתמשים לראות תמונת מצב של תיבת הדואר הנכנס שלהם. כדי שזה יקרה, צריך להפעיל את RemoteViewsFactory ואת תצוגת האוסף כדי לאחזר ולהציג נתונים חדשים.

כדי לעשות את זה, משתמשים בפקודה AppWidgetManager כדי להתקשר אל notifyAppWidgetViewDataChanged(). השיחה הזו גורמת להחזרת קריאה (callback) לשיטה onDataSetChanged() של האובייקט RemoteViewsFactory, וכך אפשר לאחזר נתונים חדשים.

אפשר לבצע פעולות שדורשות הרבה משאבים באופן סינכרוני בתוך פונקציית הקריאה החוזרת onDataSetChanged(). מובטח שהקריאה הזו תושלם לפני אחזור המטא-נתונים או נתוני הצפייה מ-RemoteViewsFactory. אפשר גם לבצע פעולות שדורשות הרבה משאבים בשיטה getViewAt(). אם הקריאה הזו נמשכת זמן רב, תצוגת הטעינה – שצוינה בשיטה getLoadingView() של האובייקט RemoteViewsFactory – מוצגת במיקום המתאים בתצוגת האוסף עד שהיא מוחזרת.

שימוש ב-RemoteCollectionItems כדי להעביר אוסף ישירות

ב-Android 12 (רמת API 31) נוספה השיטה setRemoteAdapter(int viewId, RemoteViews.RemoteCollectionItems items), שמאפשרת לאפליקציה להעביר אוסף ישירות כשמאכלסים תצוגת אוסף. אם מגדירים את המתאם באמצעות השיטה הזו, לא צריך להטמיע את RemoteViewsFactory ולא צריך לקרוא ל-notifyAppWidgetViewDataChanged().

בנוסף לכך שהגישה הזו מקלה על מילוי המתאם, היא גם מבטלת את זמן האחזור של מילוי פריטים חדשים כשמשתמשים גוללים למטה ברשימה כדי לחשוף פריט חדש. מומלץ להשתמש בגישה הזו להגדרת המתאם אם קבוצת הפריטים באוסף קטנה יחסית. עם זאת, לדוגמה, הגישה הזו לא מתאימה אם האוסף מכיל מספר רב של Bitmaps שמועברים אל setImageViewBitmap.

אם האוסף לא משתמש בפריסות קבועות – כלומר, אם פריטים מסוימים מופיעים רק לפעמים – צריך להשתמש ב-setViewTypeCount כדי לציין את המספר המקסימלי של פריסות ייחודיות שהאוסף יכול להכיל. כך אפשר להשתמש במתאם שוב בעדכונים של הווידג'ט של האפליקציה.

דוגמה להטמעה של אוספים פשוטים של RemoteViews.

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()
);