ווידג'טים של אוספים מתמחים בהצגת רכיבים רבים מאותו סוג, כמו כאוספים של תמונות מאפליקציית גלריה, כתבות מאפליקציית חדשות, הודעות מאפליקציית תקשורת. ווידג'טים של אוספים מתמקדים בדרך כלל בשני שימושים מקרים: עיון באוסף ופתיחת אלמנט מהאוסף תצוגת פרטים. ווידג'טים של אוספים יכולים לגלול אנכית.
הווידג'טים האלה משתמשים ב-RemoteViewsService
כדי להציג אוספים שמגובים בנתונים מרוחקים, למשל מספק תוכן. הווידג'ט מציג את הנתונים באמצעות אחד מסוגי התצוגות הבאים, שנקראים תצוגות אוסף:
ListView
- תצוגה שבה מוצגים פריטים רשימה של גלילה אנכית.
GridView
- תצוגה שבה מוצגים פריטים רשת גלילה דו-ממדית.
StackView
- כרטיס מוערם לראות אותו - כמו רולודקס, שבו המשתמש יכול להניע את חזית המסך כלפי מעלה או כלפי מטה כדי לראות את הכרטיס הקודם או הבא, בהתאמה.
AdapterViewFlipper
ViewAnimator
פשוט שמבוסס על מתאם, שמציג אנימציה בין שתי תצוגות או יותר. רק ילד אחד מוצג בכל פעם.
תצוגות האוספים האלה מציגות אוספים שמגובים על ידי נתונים מרחוק, לכן הן
להשתמש ב-Adapter
כדי לקשר את המשתמש שלהם
לנתונים שלהם. Adapter
מקשר בין פריטים בודדים מקבוצת נתונים לבין אובייקטים בודדים של View
.
מכיוון שתצוגות האוספים האלה נתמכות במתאמים, מסגרת Android חייבת לכלול ארכיטקטורה נוספת כדי לתמוך בשימוש בהן בווידג'טים. בהקשר של ווידג'ט, הערך Adapter
מוחלף ב-RemoteViewsFactory
, שהוא מעטפת דקה של ממשק Adapter
. כשנשלחת בקשה עבור
פריט ספציפי באוסף, הפונקציה RemoteViewsFactory
יוצרת ומחזירה
הפריט עבור האוסף
אובייקט RemoteViews
. כדי לכלול תצוגת אוסף בווידג'ט, מטמיעים את RemoteViewsService
ואת RemoteViewsFactory
.
RemoteViewsService
הוא שירות שמאפשר למתאם מרוחק לבקש אובייקטים מסוג RemoteViews
. RemoteViewsFactory
הוא ממשק למתאם
בין תצוגת אוסף - למשל ListView
, GridView
StackView
– והנתונים הבסיסיים של התצוגה המפורטת הזו. מתוך 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
לדוגמה:

StackWidget
.הדוגמה הזו מורכבת ממקבץ של עשר תצוגות שבהן מוצגים הערכים כאפס עד תשע. לווידג'ט לדוגמה יש את ההתנהגויות העיקריות הבאות:
המשתמש יכול להחליק אנכית את התצוגה העליונה בווידג'ט כדי להציג או לתצוגה הקודמת. זו התנהגות מובנית ב-
StackView
.ללא אינטראקציה עם המשתמש, הווידג'ט מתקדם אוטומטית צפיות ברצף, כמו מצגת. הסיבה לכך היא ההגדרה
android:autoAdvanceViewId="@id/stack_view"
ב- קובץres/xml/stackwidgetinfo.xml
. ההגדרה הזו חלה על מזהה התצוגה, שהוא במקרה הזה מזהה התצוגה של תצוגת הערימות.אם המשתמש נוגע בתצוגה העליונה, הווידג'ט יציג את
Toast
ההודעה "תצוגת מגע 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
ששימש לאכלוס תצוגת האוסף המרוחק.
ספציפית, מבצעים את השלבים הבאים:
קטגוריית המשנה
RemoteViewsService
. השירות באמצעותRemoteViewsService
שמתאם מרוחק יכול לבקשRemoteViews
.בתת המחלקה
RemoteViewsService
, צריך לכלול מחלקה שמממשת את ממשקRemoteViewsFactory
.RemoteViewsFactory
הוא ממשק למתאם בין תצוגת אוסף מרחוק – כמוListView
,GridView
,StackView
– לבין הנתונים הבסיסיים של התצוגה הזו. שלך אחראי ליצור אובייקטRemoteViews
לכל של הכיתובים במערך הנתונים. הממשק הזה הוא wrapper צר סביבAdapter
.
לא תוכלו להסתמך על מופע אחד של השירות, או על נתונים כלשהם שהוא מכיל, כדי
עקביים. אל תשמרו נתונים ב-RemoteViewsService
אלא אם הם סטטיים. אם המיקום
שרוצים שנתוני הווידג'ט יישארו, הגישה הטובה ביותר היא להשתמש
ContentProvider
שהנתונים שלו
נמשכת מעבר למחזור החיים של התהליך. לדוגמה, ווידג'ט של חנות מכולת
תאחסן את המצב של כל פריט ברשימת מכולת במיקום קבוע, כגון
מסד נתונים של SQL.
התוכן העיקרי של הטמעת RemoteViewsService
הוא RemoteViewsFactory
שלה, שמתואר בקטע הבא.
ממשק RemoteViewsFactory
המחלקה בהתאמה אישית שמטמיעה את הממשק RemoteViewsFactory
מספקת לווידג'ט את הנתונים של הפריטים באוסף שלו. כדי לעשות את זה,
משלבת את קובץ פריסת ה-XML של פריט הווידג'ט עם מקור של נתונים. המקור הזה של
נתונים יכולים להיות כל דבר, ממסד נתונים ועד מערך פשוט. במדגם StackWidget
, מקור הנתונים הוא מערך של WidgetItems
. RemoteViewsFactory
פועל כמתאם להדבקת הנתונים בתצוגת האוסף המרוחק.
שתי השיטות החשובות ביותר שצריך להטמיע עבור
RemoteViewsFactory
כיתות משנה
onCreate()
וגם
getViewAt()
.
המערכת קוראת ל-onCreate()
כשיוצרים את המפעל בפעם הראשונה.
כאן מגדירים את כל החיבורים או סמנים אל מקור הנתונים. לדוגמה, בדוגמה StackWidget
נעשה שימוש ב-onCreate()
כדי לאתחל מערך של אובייקטים מסוג WidgetItem
. כשהווידג'ט שלך פעיל, המערכת ניגשת אליהם
משתמשים במיקום האינדקס שלהם במערך, ומציגים את הטקסט שהם
מכילים.
לפניכם קטע מההטמעה של RemoteViewsFactory
בדוגמה StackWidget
, שבו מוצגים חלקים מהשיטה 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
שצוין במערך הנתונים. הנה קטע מההטמעה של RemoteViewsFactory
בדוגמה 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; }
הוספת התנהגות לפריטים בודדים
בקטעים הקודמים מוסבר איך לקשר את הנתונים לאוסף הווידג'טים. אבל מה קורה אם רוצים להוסיף התנהגות דינמית לפריטים הספציפיים בתצוגת אוסף?
כמו שמתואר במאמר טיפול באירועים באמצעות onUpdate()
class, אתם בדרך כלל משתמשים
setOnClickPendingIntent()
כדי להגדיר את התנהגות הקליק של אובייקט, למשל
לגרום ללחצן להפעיל Activity
. אבל
גישה זו אינה מותרת לצפיות צאצא בפריט אוסף מסוים.
לדוגמה, אפשר להשתמש בsetOnClickPendingIntent()
כדי להגדיר לחצן גלובלי
בווידג'ט של Gmail שמפעיל את האפליקציה, למשל, אבל לא
פריטים בודדים ברשימה.
במקום זאת, כדי להוסיף התנהגות קליקים לפריטים ספציפיים באוסף, משתמשים ב-setOnClickFillInIntent()
. התהליך הזה כולל הגדרה של תבנית Intent בהמתנה עבור
בתצוגת האוסף ואז להגדיר הפניה למילוי פרטים לגבי כל פריט
אוסף דרך RemoteViewsFactory
.
בקטע הזה נעזר בדוגמה StackWidget
כדי להסביר איך מוסיפים התנהגות לפריטים ספציפיים. בדוגמה StackWidget
, אם המשתמש נוגע בתצוגה העליונה,
בווידג'ט מוצגת ההודעה Toast
"תצוגת מגע n", כאשר n הוא
האינדקס (המיקום) של התצוגה שאליה נגעה. כך זה עובד:
המחלקה
StackWidgetProvider
– תת-מחלקה שלAppWidgetProvider
– יוצרת כוונה בהמתנה עם פעולה מותאמת אישית שנקראתTOAST_ACTION
.כשהמשתמש נוגע בצפייה, הכוונה מופעלת והיא משודרת
TOAST_ACTION
השידור הזה נתפס על ידי השיטה
onReceive()
של הכיתהStackWidgetProvider
, והווידג'ט מציג את ההודעהToast
לתצוגה שנגעו בה. הנתונים של פריטי האוסף סופקו על ידיRemoteViewsFactory
באמצעותRemoteViewsService
.
הגדרת התבנית של כוונה בהמתנה
StackWidgetProvider
(
תת-מחלקה AppWidgetProvider
)
מגדיר אובייקט Intent בהמתנה. אי אפשר להגדיר פריטים ספציפיים באוסף
כוונות בהמתנה. במקום זאת, האוסף כולו מגדיר תבנית של כוונה בהמתנה, והפריטים הנפרדים מגדירים כוונה למלא כדי ליצור התנהגות ייחודית לכל פריט בנפרד.
הכיתה הזו מקבלת גם את השידור שנשלח כשהמשתמש נגע בתצוגה. האירוע הזה מעובד בשיטה 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
ואיך אפשר להפעיל עדכונים:

RemoteViewsFactory
במהלך העדכונים.ווידג'טים שמשתמשים בקולקציות יכולים לספק למשתמשים תוכן עדכני. עבור
הווידג'ט של Gmail מספק למשתמשים תמונת מצב של תיבת הדואר הנכנס שלהם. כדי לעשות את זה
אפשרי, מפעילים את RemoteViewsFactory
ואת תצוגת האוסף כדי לאחזר
להציג נתונים חדשים.
כדי לעשות את זה משתמשים
AppWidgetManager
כדי להתקשר
notifyAppWidgetViewDataChanged()
הקריאה הזו תוביל לקריאה חוזרת (callback) לאובייקט RemoteViewsFactory
שלך
onDataSetChanged()
, שמאפשר לאחזר נתונים חדשים.
אפשר לבצע פעולות עתירות עיבוד באופן סינכרוני
התקשרות חזרה onDataSetChanged()
. אין לך מה לדאוג, השיחה תסתיים
לפני שהמטא-נתונים או נתוני התצוגה אוחזרו מה-RemoteViewsFactory
. אפשר גם לבצע פעולות עיבוד עתירות בתוך השיטה getViewAt()
. אם השיחה נמשכת זמן רב, תצוגת הטעינה שמצוינת על ידי
של אובייקט RemoteViewsFactory
getLoadingView()
method - מוצגת במיקום המתאים של תצוגת האוסף.
עד שהוא יחזור.
שימוש ב- 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() );